Convert a Date string to ISO format using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Convert a Date string to ISO format using JavaScript #

To convert a date string to ISO format:

  1. Pass the date string to the Date() constructor.
  2. Call the toISOString() method on the Date object.
  3. The toISOString method returns an ISO 8601 formatted string, that represents the given date.
index.js
const dateStr = '2022-07-21'; const date = new Date(dateStr); const iso = date.toISOString(); console.log(iso); // 👉️ "2022-07-21T00:00:00.000Z"

We passed the date string to the Date() constructor to create a Date object.

We then got the ISO formatted representation of the date string by calling the toISOString method on the Date object.

If your date string is not formatted in a way that the Date() constructor can understand, you have 2 options:

  • Format the date string as YYYY-MM-DDTHH:mm:ss.sssZ, e.g. 2022-07-21T00:00:00.000Z.
  • Format the date string in a way that the Date() constructor can understand, e.g. YYYY-MM-DD.

For example, if you have a date string formatted as YYYY-MM-DD, you can just append THH:mm:ss.sssZ.

index.js
const dateStr = '2022-07-21'; const isoStr = dateStr + 'T00:00:00.000Z'; console.log(isoStr); // 👉️ "2022-07-21T00:00:00.000Z"

Here is an example, where we split the string and add leading zeros to the month and date components to get a valid ISO string.

index.js
// 👇️ formatted as m/d/yyyy const dateStr = '7/24/2022'; function padTo2Digits(num) { return num.toString().padStart(2, '0'); } const [month, date, year] = dateStr.split('/'); const isoStr = `${year}-${padTo2Digits(month)}-${padTo2Digits( date, )}T00:00:00.000Z`; console.log(isoStr); // 👉️ "2022-07-24T00:00:00.000Z"

We used the split method to split the date string on each forward slash /.

We used array destructuring to assign the substrings containing the month, date and year to variables.

The month and date values could be single-digit (lower than 10), so we used the padTo2Digits function to add a leading zero if necessary.

The result is a valid ISO 8601 string, formatted as YYYY-MM-DDTHH:mm:ss.sssZ.

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.