我有一个日期格式Sun May 11,2019。如何将其转换为2019-05-11使用JavaScript?
Sun May 11,2019
2019-05-11
function taskDate(dateMilli) { var d = (new Date(dateMilli) + '').split(' '); d[2] = d[2] + ','; return [d[0], d[1], d[2], d[3]].join(' '); } var datemilli = Date.parse('Sun May 11,2019'); console.log(taskDate(datemilli));
上面的代码为我提供了相同的日期格式sun may 11,2019。我怎样才能解决这个问题?
sun may 11,2019
你可以做:
function formatDate(date) { var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [year, month, day].join('-'); }
用法示例:
alert(formatDate('Sun May 11,2019'));
输出: