我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?


当前回答

一个衬线(2022),带正确的时区偏移

var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", "");

// YearMonthDay var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", ""); console.log("YearMonthDay"); console.log(dateDisplay); // Year-Month-Day var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10); console.log("Year-Month-Day"); console.log(dateDisplay); // Year-Month-Day Hour:Minute:Second var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " "); console.log("Year-Month-Day Hour:Minute:Second"); console.log(dateDisplay); // Year-Month-Day Hour-Minute-Second var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " ").replaceAll(":", "-"); console.log("Year-Month-Day Hour-Minute-Second"); console.log(dateDisplay); // ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON(); console.log("ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ"); console.log(dateDisplay);

其他回答

var dateDisplay = new Date( 2016-11-09 05:27:00 UTC );
dateDisplay = dateDisplay.toString()
var arr = (dateDisplay.split(' '))
var date_String =  arr[0]+','+arr[1]+' '+arr[2]+' '+arr[3]+','+arr[4]

这将显示像Wed,Nov 09 2016,10:57:00这样的字符串

如果使用AngularJs(最多1.5),你可以使用日期过滤器:

var formattedDate = $filter('date')(myDate, 'yyyyMMdd')

回答另一个简单性和可读性的问题。 此外,不鼓励使用新方法编辑现有的预定义类成员:

function getDateInYYYYMMDD() {
    let currentDate = new Date();

    // year
    let yyyy = '' + currentDate.getFullYear();

    // month
    let mm = ('0' + (currentDate.getMonth() + 1));  // prepend 0 // +1 is because Jan is 0
    mm = mm.substr(mm.length - 2);                  // take last 2 chars

    // day
    let dd = ('0' + currentDate.getDate());         // prepend 0
    dd = dd.substr(dd.length - 2);                  // take last 2 chars

    return yyyy + "" + mm + "" + dd;
}

var currentDateYYYYMMDD = getDateInYYYYMMDD();
console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);

Moment.js可以成为你的朋友

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');

这里很多答案都使用toisostring函数。这个函数在输出之前将时间转换为zulu时间,这可能会导致问题。

function datestring(time) {
    return new Date(time.getTime() - time.getTimezoneOffset()*60000).toISOString().slice(0,10).replace(/-/g,"")
}

mydate = new Date("2018-05-03")
console.log(datestring(mydate))

datestring函数修复了时区问题,或者更好的是,你可以通过使用zulu时间来避免整个问题:

mydate = new Date("2018-05-03Z")
// mydate = new Date(Date.UTC(2018,5,3))
console.log(mydate.toISOString().slice(0,10).replace(/-/g,""))