Borislav Hadzhiev
Wed Jan 19 2022·2 min read
Photo by Jezael Melgoza
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.
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.
// 👇️ ['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.
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.
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.
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.
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.
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