Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a date as ISO 8601 in moment.js?

People also ask

How do I change the date format in a moment?

moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format. This example formats a date as a four-digit year, followed by a hyphen, followed by a two-digit month, another hyphen, and a two-digit day.

What time zone is ISO 8601?

Time zones in ISO 8601 are represented as local time (with the location unspecified), as UTC, or as an offset from UTC.

What is ISO date format in JavaScript?

The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ.


moment().toISOString(); // or format() - see below

http://momentjs.com/docs/#/displaying/as-iso-string/

Update Based on the answer: by @sennet and the comment by @dvlsg (see Fiddle) it should be noted that there is a difference between format and toISOString. Both are correct but the underlying process differs. toISOString converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds (YYYY-MM-DD[T]HH:mm:ss.SSS[Z]). On the other hand, format uses the default format (YYYY-MM-DDTHH:mm:ssZ) without milliseconds and maintains the timezone offset.

I've opened an issue as I think it can lead to unexpected results.


Use format with no parameters:

var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"

(http://jsfiddle.net/8gvhL1dz/)


Also possible with vanilla JS

new Date().toISOString() // "2017-08-26T16:31:02.349Z"

When you use Mongoose to store dates into MongoDB you need to use toISOString() because all dates are stored as ISOdates with miliseconds.

moment.format() 

2018-04-17T20:00:00Z

moment.toISOString() -> USE THIS TO STORE IN MONGOOSE

2018-04-17T20:00:00.000Z

var date = moment(new Date(), moment.ISO_8601);
console.log(date);