Get an ISO Date string without Time using JavaScript

avatar

Borislav Hadzhiev

Tue Jan 18 20222 min read

banner

Photo by Giau Tran

Get an ISO Date string without Time using JavaScript #

Use the split() method to get an ISO date string without time, e.g. const [withoutT] = '2022-11-14T00:55: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 [withoutTime] = date.toISOString().split('T'); console.log(withoutTime); // 👉️ 2022-01-18 // ✅ If you have a plain ISO string const [withoutT] = '2022-11-14T00:55:31.820Z'.split('T'); console.log(withoutT); // 👉️ "2022-11-14"

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

index.js
// 👇️ ['2022-11-14', '00:55:31.820Z'] console.log('2022-11-14T00:55: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
// ✅ If you have a plain ISO string const [withoutT] = '2022-11-14T00:55:31.820Z'.split('T'); console.log(withoutT); // 👉️ "2022-11-14"

Here is an example that shows how array destructuring works.

index.js
const [one, two] = [1, 2]; console.log(one); // 👉️ 1 console.log(two); // 👉️ 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 [, two] = [1, 2]; console.log(two); // 👉️ 2

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

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

index.js
const [withoutT] = '2022-11-14T00:55:31.820Z'.split('T'); console.log(withoutT); // 👉️ "2022-11-14" const newDate = new Date(withoutT); // 👇️ Mon Nov 14 2022 02:00:00 console.log(newDate);

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 [withoutT] = '2022-11-14T00:55:31.820Z'.split('T'); console.log(withoutT); // 👉️ "2022-11-14" const newDate = new Date(withoutT + 'T00:00:00'); // 👇️ Mon Nov 14 2022 00:00:00 console.log(newDate);
Use the search field on my Home Page to filter through my more than 1,000 articles.