HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

Format JavaScript date as yyyy-mm-dd

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
yyyyformatdatejavascript

Problem

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?



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));




The code above gives me the same date format, sun may 11,2014. How can I fix this?

Solution

You can do:



`function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();

if (month.length



Usage example:

console.log(formatDate('Sun May 11,2014'));


Output:

2014-05-11


Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/

Code Snippets

console.log(formatDate('Sun May 11,2014'));

Context

Stack Overflow Q#23593052, score: 998

Revisions (0)

No revisions yet.