Vlad
Vlad

Reputation: 511

How to compare two dates in different formats

I have a two dates in one format 19/02/2026, 07/02/2012 and third date in

2021-05-19T12:51:11.630Z

It's YYYY-MM-DDTHH:mm:ss.SSSSZ. And i need to check third date if it is between those to dates. But the problem is that i cannot find way how to do it with different formats. I tried to use moment() isBetween, isBefore(), isAfter() functions but it didn't work correctly because of different formats

I tried to convert them all to miliseconds

moment('19/02/2026').valueOf() 

But from time to time instead of miliseconds i recieve NaaN value. I also tried to use

Date().parse()

But it gives Invalid Date most of the time. I could do something like this, but i think it's wrong way.

let currentDate = moment( moment('2021-05-19T12:51:11.630Z').format('DD/MM/YYYY'))

Is there are any simple ways to do it with Date or moment ?

Upvotes: -1

Views: 61

Answers (1)

Richard Deeming
Richard Deeming

Reputation: 31198

To parse a string which is not either an RFC2822 or ISO8601 format, you will need to specify the format to use:

const d = moment('19/02/2026', 'DD/MM/YYYY');

Rather than using valueOf, you can test whether one moment instance is between two other moment instances by using isBetween:

const startDate = moment('07/02/2012', 'DD/MM/YYYY');
const endDate = moment('19/02/2026', 'DD/MM/YYYY');
const dateToTest = moment('2021-05-19T12:51:11.630Z');
if (dateToTest.isBetween(startDate, endDate)) {
    alert("Between");
} else {
    alert("Not between");
}

String + Format | Moment.js | Docs
Is Between | Moment.js | Docs

Upvotes: 0

Related Questions