convert iso string to datetime javascript

Convert ISO String to Datetime in JavaScript

If you have an ISO string and want to convert it to a datetime object in JavaScript, you can use the built-in Date object.

Method 1: Using Date constructor

You can use the Date constructor to create a new Date object with the ISO string as its argument. Here's an example:


const isoString = '2022-05-12T03:30:00Z';
const datetime = new Date(isoString);
console.log(datetime); // Output: Thu May 12 2022 08:00:00 GMT+0530 (India Standard Time)

The Date object will automatically parse the ISO string and convert it to the local timezone.

Method 2: Using moment.js library

If you prefer using a library, you can use moment.js to parse the ISO string and convert it to a datetime object. Here's an example:


const isoString = '2022-05-12T03:30:00Z';
const datetime = moment(isoString).toDate();
console.log(datetime); // Output: Thu May 12 2022 08:00:00 GMT+0530 (India Standard Time)

The moment function returns a moment object, which can be converted to a Date object using the toDate() method.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe