Reputation: 119
My input is get via an API, and I have this array with the following date format as strings:"2022-06-29T15:30:00+00:00", "2022-07-01T09:00:00+00:00", "2022-07-05T16:00:00+00:00".
I want to transform those date in another format (ex for the first one: 29.06.2022 (DD.MM.YYYY)).
Also, I want to compare dates to sort the array. How can I do this? Do I need to convert it into a Date object? (vanilla JS, no frameworks).
Upvotes: 1
Views: 952
Reputation: 101
You can consider doing it like this:
const str = "2022-06-29T15:30:00+00:00";
const date = new Date(str);
console.log(date); // 👉️ Wed Jun 29 2022 22:30:00
As for sorting array based on dates, you can take a look at How to sort an object array by date property.
Upvotes: 2
Reputation: 61
let dateStr = "2022-06-29T15:30:00+00:00";
let getDate = dateStr.split('T')[0];
const date = new Date(getDate);
Upvotes: 0
Reputation: 25398
You can first sort the dates using sort method
dateArr.sort((a, b) => new Date(a) - new Date(b))
and then map
over the array
const dateArr = [
'2022-06-29T15:30:00+00:00',
'2022-07-01T09:00:00+00:00',
'2022-07-05T16:00:00+00:00',
];
const result = dateArr
.sort((a, b) => new Date(a) - new Date(b))
.map((str) => str.split('T')[0].split('-').reverse().join('-'));
console.log(result)
Upvotes: 1