Convert an ISO string to a Date object in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Convert an ISO string to a Date object in JavaScript #

Use the Date() constructor to convert an ISO string to a date object, e.g. new Date('2023-07-21T09:35:31.820Z'). The Date() constructor will easily parse the ISO 8601 string and will return a Date object.

index.js
const isoStr1 = '2022-07-21T09:35:31.820Z'; // ✅ Create Date object (setting date to UTC) const date1 = new Date(isoStr1); console.log(date1); // 👉️ Thu Jul 21 2022 12:35:31 GMT+0300 // ✅ Create Date object (setting date to local time) const date2 = new Date(isoStr1.slice(0, -1)); console.log(date2); // 👉️ Thu Jul 21 2022 09:35:31 GMT+0300

We used the Date() constructor to create a Date object from an ISO string.

In the first example, we directly passed the ISO string to the Date constructor.

The time in the ISO string is 09:35:31, however the created Date object shows 12:35:31.

This is because my time zone is 3 hours ahead of Coordinated Universal time (UTC).

In the second example, we used the slice method to remove the Z from the end of the ISO string and created a Date object in local time - 09:35:31 (exact same time as our ISO string).

index.js
const isoStr1 = '2022-07-21T09:35:31.820Z'; // ✅ Create Date object (setting date to local time) const date2 = new Date(isoStr1.slice(0, -1)); console.log(date2); // 👉️ Thu Jul 21 2022 09:35:31 GMT+0300

If the Z is present, the Date is set to UTC. If the Z is not present, it's set to local time (this only applies if time is provided).

The Z at the end of the ISO string means UTC, in other words, an offset from UTC of zero hours, minutes and seconds.

Here is an easy way to visualize things.

index.js
const isoStr1 = '2022-07-21T09:35:31.820Z'; // ✅ Create Date object (setting date to UTC) const date1 = new Date(isoStr1); console.log(date1); // 👉️ Thu Jul 21 2022 12:35:31 GMT+0300 console.log(date1.getUTCHours()); // 👉️ 9 // ✅ Create Date object (setting date to local time) const date2 = new Date(isoStr1.slice(0, -1)); console.log(date2); // 👉️ Thu Jul 21 2022 09:35:31 GMT+0300 console.log(date2.getUTCHours()); // 👉️ 6

When we pass the ISO string directly to the Date() constructor, the getUTC* methods return the exact same time components that are present in the ISO string.

For consistency, you should mostly use local time when you have to render a date and time to the user, but you should store the actual values in UTC (valid ISO 8601 strings).

For example, if you store a local time (without the Z) of midnight (00:00) in your database, you wouldn't know if that's midnight in Tokyo (Japan), in Paris (France), in New York (US), etc. These are all different moments that are hours apart.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.