简体   繁体   中英

Changing date format using Jquery

I have date got from a API like this 2018-08-27T09:28:53, now I want to convert it to a format like August 27, 2018.

I have tried using this

var d = new Date(val.date);
d = d.toDateString();

the above code gives a date like Mon Jul 27 2018. How can I add the comma and separate the month day and year?

Is there a better way to format iso 8601 date to desired format, for me like August 27, 2018.

The easiest would be that you use options with toLocaleDateString

var d = new Date(val.date);
var options = { year: 'numeric', month: 'long', day: 'numeric' };
d = d.toLocaleDateString("en-US", options)

 var d = new Date(); var options = { year: 'numeric', month: 'long', day: 'numeric' }; console.log( d.toLocaleDateString('en-US', options) ); 

The easiest way for you is to use date.js :

var date = new Date('2018-08-27');
var newDate = date.toString('dd-MM-yy');

Or you can Nativity:

var dateAr = '2018-08-27'.split('-');
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);

console.log(newDate);

Pure js:

 let objDate = new Date(), month = objDate.toLocaleString('en-us', { month: 'long' }), day = objDate.getDate(), year = objDate.getFullYear() console.log(`${month} ${day}, ${year}`) 

or

 let objDate = new Date(), date = objDate.toLocaleString('en-us', { year: 'numeric', month: 'long', day: 'numeric' }) console.log(date) 

More about toLocaleString.

You can use some plugin for that, like momentjs , or use following code:

function formatDate(date) {
    var months = [
        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"
    ];

    var d = date.getDate(),
        m = date.getMonth(),
        y = date.getFullYear();

    return months[m] + ', ' + d + ' ' + y;
}

console.log(formatDate(new Date()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM