-1

When I do new Date() in JS I get:

Thu Jul 26 2018 08:09:57 GMT+0200 (Central European Summer Time)

How can I get it in this format along with the included Z at the end?

2016-05-26t16:53:22.313Z
martinbshp
  • 1,073
  • 4
  • 22
  • 36

2 Answers2

2

Though there are other answers available, I recently found that you can call toJSON() on the date object to get the ISO formatted string:

console.log((new Date()).toJSON());
31piy
  • 23,323
  • 6
  • 47
  • 67
  • 1
    I'd prefer `Date.prototype.toISOString()` as it's quite explicit. The exact implementation of `toJSON()` could change in future – Phil Jul 26 '18 at 06:29
  • @Phil -- thank you for your comment. I didn't find anything such on the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON). Do you have some references handy? – 31piy Jul 26 '18 at 06:30
  • It's right there in the link you provided ~ _"Calling `toJSON()` returns a string (using `toISOString()`) representing the Date object's value."_. If you want an ISO string, you should probably call `toISOString`. At the moment, it's only an implementation detail that means both methods produce the same result – Phil Jul 26 '18 at 06:32
  • @Phil -- Right. Wanted a reference for the phrase _could change in future_ in your first comment. – 31piy Jul 26 '18 at 06:33
  • 1
    There's nothing saying it won't either :) – Phil Jul 26 '18 at 06:34
2

You can use toISOString to get this:

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

console.log(new Date().toISOString());
NullPointer
  • 7,094
  • 5
  • 27
  • 41