How To Convert An ISO String To A Date Object In JavaScript

Convert an ISO string to a Date object in JavaScript

Are you looking for a way to convert an ISO string to a Date object in Javascript? I will show you two methods for this problem: the Date constructor and slice() method in this article.

Convert an ISO string to a Date object in JavaScript

Using the Date() constructor

We will create a string in ISO format to convert that string to a Date object. Then, put the string into the Date() constructor, returning a Date object from the ISO string. 

Code sample:

// Create a dateObj1 object from the isoString1 in UTC
let isoString1 = '2022-11-02T20:16:28.175Z'; 
let dateObj1 = new Date(isoString1);


// Create a dateObj2 object from the isoString2 in UTC
let isoString2 = '2022-11-02T03:18:32.182Z';
let dateObj2 = new Date(isoString2);



Thu Nov 03 2022 03:16:28 GMT+0700 (Indochina Time)
Wed Nov 02 2022 10:18:32 GMT+0700 (Indochina Time)

In the first example, we get ‘Thu Nov 03 2022 03:16:28’. It’s different from the original ISO string because my time zone is UTC+0700, so the time is added 7 hours which means from ‘20:16:28.175’ to ‘03:16:28’ am the next day.

In the second example, you can see it’s still the same day, but the time from ‘03:18:32.182’ has been increased by 7 hours to ‘10:18:32’.

Using the slice() method

So, If you want to return the same time in the original ISO string, we have a second way: remove the ‘Z’ character at the end of the ISO string. Because z is set to UTC, if we remove the ‘Z’ it will not be set to UTC but it will return at the same time as we have given.

We use the slice() function to extract a new string that does not include the ‘Z’.

Code sample:

let isoStr3 = '2022-11-02T08:19:28.384Z';
let isoStr4 = '2022-11-02T23:20:47.126Z';
// Create dates object in local time
let dateObj3 = new Date(isoStr3.slice(0, -1));
let dateObj4 = new Date(isoStr4.slice(0, -1));


Wed Nov 02 2022 08:19:28 GMT+0700 (Indochina Time)
Wed Nov 02 2022 23:20:47 GMT+0700 (Indochina Time)


Using the ‘Date’ constructor and the slice() function to convert an ISO string to a Date object in Javascript will make it more convenient for you to retrieve the correct local time than in UTC format. Choose the best option for your case. If you want to learn more Javascript lessons, follow here. Thank you for reading, have a nice day!

Maybe you are interested:

Leave a Reply

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