Javascript Convert ISO String to a Date object

Sometimes, you need to work with an ISO String containing a date like YYYY-MM-DD format.

To convert an ISO string to a Date object in JavaScript, you need to call the Date() constructor and pass the ISO string as its argument.

Let’s see an example. Suppose you want to convert an ISO date string for 27th August 2022:

let isoString = "2022-08-27T01:00:00.000Z"

let myDate = new Date(isoString);

console.log(myDate) // Sat Aug 27 2022 05:00:00 GMT+0400

Here, you can see that the date string is converted into a Date object, and the timezone of the Date is adjusted to your local time zone.

My current local time zone is GMT+4, while the date string is in UTC time zone (GMT+0)

If you don’t want the time to adjust to your local time zone, you need to remove the ‘Z’ letter at the end of your date string.

You can use the replace() method to remove the ‘Z’ letter as shown below:

let isoString = "2022-08-27T01:00:00.000Z"

let myDate = new Date(isoString.replace('Z', ''));

console.log(myDate) // Sat Aug 27 2022 01:00:00 GMT+0400

Now you can see that the time is 00:00:00. JavaScript thinks the ISO string is already local time.

Sometimes, you only want the date part without the time part.

You can use the split() method to split the string at the letter ‘T’ and pass the first part of the array:

let isoString = "2022-08-27T00:00:00.000Z"

let isoArray = isoString.split('T');

let myDate = new Date(isoArray[0]);

console.log(myDate) // Sat Aug 27 2022 04:00:00 GMT+0400

Note that when you didn’t pass the time part, JavaScript will put midnight (00:00:00) as the time part for the Date object.

The time part also gets adjusted to the local time zone.

Convert a Date object to an ISO string

You can convert the Date object back to an ISO string by calling the toISOstring() method from the Date object:

let myDate = new Date('2022-08-27T01:00:00.000Z');

let isoString = myDate.toISOString();

console.log(isoString); // 2022-08-27T01:00:00.000Z

Now you’ve learned how to work with ISO string in JavaScript. Nice work!

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.