Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format an ISO 8601 date to a more readable format, using Javascript? [duplicate]

I'm using an API to call a date from a post.

Dates are returned in ISO 8601 format :

2015-11-09T10:46:15.097Z

I want my dates to be formatted like this :

09/11/2015

Then, later, I want to insert them into my HTML, like this :

$(data).each(function(){
    var html = '<randomhtml> '+this.created_at+' <randomhtml>
    $('#stream').append(html);
});

Does anyone know how I can change my date to right format?

like image 784
Bradley Jarvis Avatar asked Mar 09 '16 13:03

Bradley Jarvis


3 Answers

The easiest would be to just work with the string

$(data).each(function(){

    var date = this.created_at.split('T') // split on the "T"   -> ["2015-11-09", "10:..."]
                              .shift()    // get the first part -> "2015-11-09"
                              .split('-') // split again on "-" -> ["2015", "11", "09"]
                              .reverse()  // reverse the array  -> ["09", "11", "2015"]
                              .join('/')  // join with "/"      -> "09/11/2015"

    var html = '<randomhtml> ' + date + ' <randomhtml>';
    $('#stream').append(html);
});

As it's a UTC date, just passing it do new Date() would add the difference of the timezone, and not always output the correct date.
If you need to validate the date, there are regexes for checking valid UTC dates.

like image 53
adeneo Avatar answered Nov 19 '22 20:11

adeneo


this can be solve your problem

var date = new Date('2015-11-09T10:46:15.097Z');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());

output will be "09/11/2015"

like image 5
Pankaj Monga Avatar answered Nov 19 '22 21:11

Pankaj Monga


For date manipulation momentjs library is very useful.

If you want to make date format dependent on users country you can additionally use formatjs.

like image 1
jkordas Avatar answered Nov 19 '22 22:11

jkordas