Explain Codes LogoExplain Codes Logo

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

javascript
moment-js
date-formatting
iso-8601
Anton ShumikhinbyAnton Shumikhin·Dec 31, 2024
TLDR

Get an ISO 8601 formatted date using moment.js with:

const isoDate = moment().toISOString();

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 π.

const date = new Date(); // Enjoying your apple pie const formattedDate = moment(date).toISOString();

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 chameleon changes color but never hides const formattedDateWithOffset = moment(date).format();

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:

// Well, who could resist vanilla! 😋 const isoDateWithVanillaJS = new Date().toISOString();

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:

// Captain, we're ready for MongoDB! const mongoDBQueryDate = moment().toISOString();

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:

// It's like opening a Swiss Bank Account! const dateFromISOString = moment("2023-03-26T00:00:00.000Z", moment.ISO_8601);

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.