How do I format a date as ISO 8601 in moment.js?
Get an ISO 8601 formatted date using moment.js with:
The output will look like: 2023-04-12T07:20:50.000Z
—an ISO 8601 formatted string that represents the current date in UTC, with precision up to milliseconds.
Method selection and rules of thumb
There are two principal methods in moment.js to convert a date to ISO 8601: .toISOString()
and .format()
.
Transforming with toISOString()
This one's as simple as eating pie—apple pie, not π.
This method transforms the date to UTC and outputs an ISO 8601 formatted string. It's akin to the built-in JavaScript Date.prototype.toISOString()
function.
Formatting with format
If you want to keep the timezone offset, use .format()
, the chameleon of date formatting.
This effectively retains your local timezone data in the ISO 8601 string.
Tips and things to keep in mind
- The
.format()
function reflects the timezone of the moment instance, while.toISOString()
always gives a UTC date. So keep an eye on timezones. - Always check if there are any open GitHub issues that might impact moment.js' date formatting.
- Stay updated with the latest version of moment.js to avail of bug fixes and improvements.
Advancing your ISO 8601 skills with moment.js
More advanced management of ISO 8601 with moment.js is also possible.
Who needs a library, anyway?
Sometimes, going back to basics, vanilla JavaScript may be all you need:
This also gives an ISO 8601 date in UTC with no library overhead—keeping it simple!
MongoDB and ISO 8601
If you're using MongoDB, where ISO 8601 formatted dates are a must:
Since MongoDB deals with dates in UTC by default, using .toISOString()
aligns perfectly with its requirements.
DateTime string extraction
And for the reverse operation, pull out a date from an ISO 8601 string:
This gets you a moment object representing the same point in time.
Considerations for implementation
- Weigh moment.js against vanilla JS to find the best fit for your unique use case.
- Remember to think of the timezone and daylight savings time when using
.format()
. - Keep in mind that
.toISOString()
normalizes the moment to UTC, which can be a boon or a bane, depending on the context.
Was this article helpful?