Search code examples
javascripthtmldatedate-formattime-format

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


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?


Solution

  • 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.