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

sennett picture sennett · Sep 8, 2014 · Viewed 251.7k times · Source

This docs mention moment.ISO_8601 as a formatting option (from 2.7.0 - http://momentjs.com/docs/#/parsing/special-formats/), but neither of these work (even 2.7.0):

var date = moment();
date.format(moment.ISO_8601); // error
moment.format(date, moment.ISO_8601); // error

(http://jsfiddle.net/b3d6uy05/1/)

How can I get an ISO 8601 from moment.js?

Answer

cyberwombat picture cyberwombat · Feb 21, 2015
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.