Salih K
Salih K

Reputation: 711

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.

Upvotes: 0

Views: 8251

Answers (4)

Илья Зелень
Илья Зелень

Reputation: 8108

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.

Upvotes: 0

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

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

Upvotes: 0

sertsedat
sertsedat

Reputation: 3600

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

Upvotes: 1

Barr J
Barr J

Reputation: 10927

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

Upvotes: 0

Related Questions