警报(dateObj)给出周三2009年12月30日00:00:00 GMT+0800

如何获得日期格式为2009/12/30?


当前回答

ES2018引入了正则表达式捕获组,你可以用它来捕获日、月和年:

const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
const results = REGEX.exec('2018-07-12');
console.log(results.groups.year);
console.log(results.groups.month);
console.log(results.groups.day);

这种方法的优点是可以捕获非标准字符串日期格式的日、月、年。

引用https://www.freecodecamp.org/news/es9——javascripts -状态- -艺术-在- 2018 - 9 - a350643f29c/

其他回答

info

如果需要2位数字的月份和日期(2016/01/01 vs 2016/1/1)

code

var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);

输出

2016/10/06

小提琴

https://jsfiddle.net/Hastig/1xuu7z7h/

信贷

更多信息来自这个答案

more

要了解更多关于.slice的信息,w3schools的自己尝试编辑器帮助我更好地了解如何使用它。

您可以简单地使用这一行代码以年-月-日格式获取日期

var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
let dateObj = new Date();

let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());

作为参考,你可以看到下面的细节

new Date().getDate()          // Return the day as a number (1-31)
new Date().getDay()           // Return the weekday as a number (0-6)
new Date().getFullYear()      // Return the four digit year (yyyy)
new Date().getHours()         // Return the hour (0-23)
new Date().getMilliseconds()  // Return the milliseconds (0-999)
new Date().getMinutes()       // Return the minutes (0-59)
new Date().getMonth()         // Return the month (0-11)
new Date().getSeconds()       // Return the seconds (0-59)
new Date().getTime()          // Return the time (milliseconds since January 1, 1970)

let dateObj = new Date(); let myDate = (dateObj.getUTCFullYear()) + “/” + (dateObj.getMonth() + 1)+ “/” + (dateObj.getUTCDate()); console.log(myDate)

为什么不使用方法toISOString()与切片或简单的toLocaleDateString()?

注意toISOString返回的时区总是零UTC偏移量,而在toLocaleDateString中它是用户代理的时区。

检查:

const d = new Date() //今天,现在 //时区0 UTC偏移量 console.log (d.toISOString()。slice(0, 10)) // YYYY-MM-DD //用户代理的时区 console.log(d.toLocaleDateString('en-CA')) // YYYY-MM-DD .log(d.toLocaleDateString('en-CA') console.log(d.toLocaleDateString('en-US')) // M/D/YYYY .log(d.toLocaleDateString('en-US') console.log(d.toLocaleDateString('de-DE')) // d.m.y yyyy .log console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY .log(d.toLocaleDateString('pt-PT')

var date = new Date().toLocaleDateString()
"12/30/2009"