且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JavaScript中将ISO日期转换为日期格式yyyy-mm-dd

更新时间:2023-01-29 10:37:57

尝试一下

date = new Date('2013-03-10T02:00:00Z');
date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();//prints expected format.

更新:-

正如评论中指出的那样,如果需要,我正在更新答案以打印日期和月份的前导零。

As pointed out in comments, I am updating the answer to print leading zeros for date and month if needed.

date = new Date('2013-08-03T02:00:00Z');
year = date.getFullYear();
month = date.getMonth()+1;
dt = date.getDate();

if (dt < 10) {
  dt = '0' + dt;
}
if (month < 10) {
  month = '0' + month;
}

console.log(year+'-' + month + '-'+dt);