Get only the Date from an ISO string in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 19, 2022

banner

Photo from Unsplash

Get only the Date from an ISO string in JavaScript #

Use the split() method to get only the date from an ISO string, e.g. const [onlyDate] = '2022-09-24T09:35:31.820Z'.split('T'). We split the string on the T character and assign the first array element to a variable to get the date component only.

index.js
const date = new Date(); // ✅ If you have a Date object const [onlyDate] = date.toISOString().split('T'); console.log(onlyDate); // 👉️ "2022-01-19" // ✅ If you have an ISO string const [onlyD] = '2022-09-24T09:35:31.820Z'.split('T'); console.log(onlyD); // 👉️ "2022-09-24"

We used the String.split method to split the ISO 8601 string on the T character.

index.js
// 👇️ ['2022-09-24', '09:35:31.820Z'] console.log('2022-09-24T09:35:31.820Z'.split('T'));

The split method returns an array of the substrings split by the provided separator.

We used array destructuring to assign the first array element (the date) to a variable.

index.js
const [onlyD] = '2022-09-24T09:35:31.820Z'.split('T'); console.log(onlyD); // 👉️ "2022-09-24"

Here is an example that shows how array destructuring works.

index.js
const [first, second] = [1, 2]; console.log(first); // 👉️ 1 console.log(second); // 👉️ 2

The variables to the left of the equal sign get assigned the array elements in the same order.

You can also use a comma to skip an array element if you don't need it.

index.js
const [, second] = [1, 2]; console.log(second); // 👉️ 2

The onlyD variable stores a date formatted as YYYY-MM-DD.

You can use this date to create a new Date object.

index.js
const [onlyD] = '2022-09-24T09:35:31.820Z'.split('T'); console.log(onlyD); // 👉️ "2022-09-24" const newDate = new Date(onlyD); console.log(newDate); // 👉️ Sat Sep 24 2022 03:00:00

Note that if you create a date without specifying time, you get a date set in UTC.

If you want to create a date in the visitor's local time, include the time.

index.js
const [onlyD] = '2022-09-24T09:35:31.820Z'.split('T'); console.log(onlyD); // 👉️ "2022-09-24" const newDate = new Date(onlyD + 'T00:00:00'); console.log(newDate); // 👉️ Sat Sep 24 2022 00:00:00
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.