Categories
JavaScript Answers

How to Format a Date as an ISO-8601 String with Moment.js?

Spread the love

Sometimes, we may want to format a date into the IS0–8601 standard format.

In this article, we’ll look at how to format a date into an ISO-8601 string with moment.js.

The toISOString Method

Moment.js comes with the toISOString method to let us format dates to ISO-8601 format.

For instance, we can write:

console.log(moment(new Date(2021, 1, 1)).toISOString())

Then we get:

'2021-02-01T08:00:00.000Z'

as a result.

The format Method

The format method also lets us format a date to an ISO-8601 date string.

For instance, we can write:

import moment from "moment";
console.log(moment(new Date(2021, 1, 1)).format());

Then we get the same result as before.

Timezone Support

We can use the Moment Timezone library to add support for time zones.

Then we can set the time zone in our app and then use the toISOString method to convert the moment object to an ISO-8601 string.

For instance, we can write:

const moment = require("moment-timezone");
moment().tz("America/Los Angeles");
console.log(moment(new Date(2021, 1, 1)).toISOString(true));

Then the console log logs:

'2021-02-01T00:00:00.000-08:00'

as a result.

Parsing ISO-8601 Dates

We can parse ISO-8601 dates with moment.js

For instance, we can write:

import moment from "moment";
console.log(moment("2021-01-01", moment.ISO_8601));

We pass in a date string in ISO-8601 format.

And we pass in the moment.ISO_8601 constant to let moment know that the date string in the first argument is an ISO-8601 date.

Conclusion

We can create and parse ISO-8601 date strings with moment.js in our JavaScript code.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Format a Date as an ISO-8601 String with Moment.js?”

I want to print dofferent timezone dates in ISO format(Ex: 2022-04-10T00:00:00.000-08:00) without using moment.js
Ex:
London = 2022-04-10T00:00:00.000+01:00
India = 2022-04-10T10:05:30.549+05:30

Leave a Reply

Your email address will not be published. Required fields are marked *