我有一个日期格式Sun May 11,2014。如何将其转换为2014-05-11使用 JavaScript?
Sun May 11,2014
2014-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,2014'); console.log(taskDate(datemilli));
上面的代码给了我相同的日期格式,sun may 11,2014. 我怎样才能解决这个问题?
sun may 11,2014
你可以做:
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('-'); } console.log(formatDate('Sun May 11,2014'));
使用示例:
console.log(formatDate('Sun May 11,2014'));
输出:
JSFiddle 上的演示:http: //jsfiddle.net/abdulrauf6182012/2Frm3/