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

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


当前回答

一行,使用解构。

创建3个字符串类型的变量:

const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-')

生成3个类型为number (integer)的变量:

const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-').map(x => parseInt(x, 10))

从那时起,你就可以很容易地以任何你喜欢的方式组合它们:

const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-');
const dateFormatted = `${year}/${month}/${day}`;

其他回答

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/

我使用这个工作,如果你传递它一个日期obj或js时间戳:

getHumanReadableDate: function(date) {
    if (date instanceof Date) {
         return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
    } else if (isFinite(date)) {//timestamp
        var d = new Date();
        d.setTime(date);
        return this.getHumanReadableDate(d);
    }
}

对于已接受的答案,1月1日将显示如下:2017/1/1。

如果你更喜欢2017/01/01,你可以使用:

var dt = new Date();
var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();

2021的答案

你可以使用本地的. tolocaledatestring()函数,它支持一些有用的参数,如区域设置(选择MM/DD/YYYY或YYYY/MM/DD格式),时区(转换日期)和格式详细选项(例如:1 vs 01 vs一月)。

例子

new Date().toLocaleDateString() // 8/19/2020

new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)

new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale

new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale

new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)

new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"});  // 09 (just the hour)

注意,有时要以特定的格式输出日期,必须找到与该格式兼容的区域设置。 您可以在这里找到本地示例:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

请注意locale只是改变格式,如果你想将特定日期转换为特定国家或城市的等效时间,那么你需要使用timezone参数。

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