9

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?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Bradley Jarvis
  • 149
  • 2
  • 7

5 Answers5

6

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.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • If you're chaining methods, might as well do it in one - `this.created_at.split("T")[0].split("-").reverse().join("/");` - although it would be a very good idea to add a comment explaining what input and output it has, and possibly some error checking to ensure the input is in the format you expect. – Niet the Dark Absol Mar 09 '16 at 13:55
  • The input and output is what the OP wants, as both are specified in the question. I used two lines to make it a little more readable. And I did check it before I posted it -> https://jsfiddle.net/1d5hf8sz/ – adeneo Mar 09 '16 at 13:56
  • I'm not saying you're wrong. I'm saying that code of this level of obscurity *should* include comments to explain its operation to future developers. The error checking is to ensure that the source data format hasn't changed from code elsewhere, which could lead to unexpected behaviour here. – Niet the Dark Absol Mar 09 '16 at 13:58
  • To reformat the string only requires one *split* (or *match*) plus one more statement for formatting. Calling 6 methods to do that does not seem sensible. – RobG Mar 10 '16 at 02:57
  • This is a terrible answer, there are plenty of cleaner ways, built into JavaScript, to handle a date in text format. -1. – dbDev Dec 27 '21 at 02:52
6

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"

Pankaj Monga
  • 179
  • 2
  • 8
1

All browsers

The most reliable way to format a date with the source format you're using, is to apply the following steps :

  1. Use your time string as input for new Date()
  2. Use .getDate(), .getMonth() and .getFullYear() to get respectively the day, month and year
  3. Paste the pieces together according to your target format

The format function below shows you the optimal way to combine those four steps :

var date = '2015-11-09T10:46:15.097Z';

function format(input) {
    var date = new Date(input);
    return [
       ("0" + date.getDate()).slice(-2),
       ("0" + (date.getMonth()+1)).slice(-2),
       date.getFullYear()
    ].join('/');
}

document.body.innerHTML = format(date); // OUTPUT : 09/11/2015

(See also this Fiddle).

Note

While this approach does work in all browsers, you'll need an additional step before new Date(input) to parse your ISO 8601 format if you need to support browsers as old as IE8--. See the accepted answer at Javascript JSON Date parse in IE7/IE8 returns NaN for a function that does exactly that.


Modern browsers only

You can also use the built-in .toLocaleDateString method to do the formatting for you. You just need pass along the proper locale and options to match the right format, which unfortunately is only supported by modern browsers (*) :

var date = '2015-11-09T10:46:15.097Z';

function format(input) {
    return new Date(input).toLocaleDateString('en-GB', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

document.body.innerHTML = format(date); // OUTPUT : 09/11/2015

(See also this Fiddle).


(*) According to the MDN, "Modern browsers" means Chrome 24+, Firefox 29+, IE11, Edge12+, Opera 15+ & Safari nightly build

Community
  • 1
  • 1
John Slegers
  • 45,213
  • 22
  • 199
  • 169
  • 1
    It is generally **not** recommended to use the Date constructor to parse strings (or Date.parse, they are equivalent) as it is unreliable. Even ISO 8601 compliant strings are not correctly parsed by all browsers in use. – RobG Mar 10 '16 at 02:54
  • 1
    @RobG : `Even ISO 8601 compliant strings are not correctly parsed by all browsers in use.` - Do you know of any sources that can confirm incorrect parsing of ISO 8601 date strings? Or any specifics on which browsers are impacted? Also, which alternative approach would you recommend? Manually parsing ISO 8601 into its components? – John Slegers Mar 10 '16 at 07:46
  • 1
    IE 8 ([*8% usage*](https://www.netmarketshare.com/browser-market-share.aspx?qprid=2&qpcustomd=0), which is 3rd highest by version and twice as common as all versions of Safari combined) will not parse ISO 8601 strings at all. Dates like 2016-02-25 are parsed as UTC by some and local by others. Manual parsing is recommended, a library can help but is not necessary if you only need to parse one format. – RobG Mar 10 '16 at 23:05
  • @RobG : Thanks for the feedback. I added a note that addresses this. – John Slegers Mar 11 '16 at 07:54
1

For date manipulation momentjs library is very useful.

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

jkordas
  • 155
  • 6
0

The simplest and most reliable way to reformat a date string is to just reformat the string. So use split (or match) to get the values and return them in the order you want, ignoring the bits you don't need, e.g.:

function isoToDMY(s) {
   var b = s.split(/\D/);
   return b[2] + '/' + b[1] + '/' + b[0];
}

document.write(isoToDMY('2015-11-09T10:46:15.097Z'));

If you want the output date to also consider the host system time zone (e.g. 2015-11-09T20:46:15Z in a timezone that is UTC+0530 will be 2015-11-10T02:16:15Z)), then you should manually parse it to a Date object and then get year, month and day values.

A library can help with parsing, but a function to parse and validate the values is only a few lines.

RobG
  • 142,382
  • 31
  • 172
  • 209