Borislav Hadzhiev
Wed Jan 19 2022·2 min read
Photo by Alexandru Zdrobău
To convert a date string to ISO format:
Date()
constructor.toISOString()
method on the Date
object.toISOString
method returns an ISO 8601 formatted string, that
represents the given date.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:
YYYY-MM-DDTHH:mm:ss.sssZ
, e.g.
2022-07-21T00:00:00.000Z
.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
.
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.
// 👇️ 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 3 substrings containing the month, date and year to variables.
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
.