Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format JavaScript date as yyyy-mm-dd

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?

like image 439
user3625547 Avatar asked May 11 '14 13:05

user3625547


People also ask

How do I get the current date in YYYY-MM-DD format in node JS?

The simplest way to convert your date to the yyyy-mm-dd format, is to do this: var date = new Date("Sun May 11,2014"); var dateString = new Date(date. getTime() - (date. getTimezoneOffset() * 60000 )) .


3 Answers

Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:

let yourDate = new Date()
yourDate.toISOString().split('T')[0]

Where yourDate is your date object.

Edit: @exbuddha wrote this to handle time zone in the comments:

const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
like image 148
Darth Egregious Avatar answered Oct 13 '22 23:10

Darth Egregious


You can do:

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

Usage example:

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

Output:

2014-05-11

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

like image 911
user3470953 Avatar answered Oct 13 '22 23:10

user3470953


I use this way to get the date in format yyyy-mm-dd :)

var todayDate = new Date().toISOString().slice(0, 10);
console.log(todayDate);
like image 328
Mitch3091 Avatar answered Oct 13 '22 22:10

Mitch3091