Categories
JavaScript Answers

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

Spread the love

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

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

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.