1

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).

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@RobG You're right. I've edited my answer.
1

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)

Comments

0
let dateStr = "2022-06-29T15:30:00+00:00";
let getDate = dateStr.split('T')[0];
const date = new Date(getDate);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.