0

I have two dates date and meeting.date coming from two APIs. I want to check, if the dates are equal.

// date = "28.02.2022";
// meeting.date = "2022-02-08 14:30:00";

const firstDate = new Date(`${date.split(".").reverse().join("-")}`);
const secondDate = new Date(`${meeting.date.split(" ")[0]}`)

firstDate.setHours(0,0,0,0);
secondDate.setHours(0,0,0,0);

console.log(firstDate, secondDate, firstDate === secondDate);

This logs me

[Log] Mon Feb 28 2022 00:00:00 GMT+0100 (CET)  – Mon Feb 28 2022 00:00:00 GMT+0100 (CET)  – false

I expect that to be true? I found the solution, setting the hours to zero here on stackoverflow, but I'd say, that this is gratuitous, as I don't pass the time the Date. Anyhow, what am I doing wrong?

PeterPan
  • 195
  • 2
  • 16
  • Go through this https://stackoverflow.com/questions/2698725/comparing-date-part-only-without-comparing-time-in-javascript – atomankion Mar 02 '22 at 07:34
  • 1
    Does this answer your question? [Comparing date part only without comparing time in JavaScript](https://stackoverflow.com/questions/2698725/comparing-date-part-only-without-comparing-time-in-javascript) – yivi Mar 07 '22 at 14:06

3 Answers3

1

You are comparing the Date objects themselves - and they will never be equal unless it is the same "object" pointed to by 2 different variables, e.g.

const dateOne = dateTwo = new Date();

You must either compare the date parts as Strings, e.g.

console.log(
  firstDate,
  secondDate,
  firstDate.toISOString().substr(0, 10) === secondDate.toISOString().substr(0, 10)
);

or compare the dates as Numbers (in milliseconds) which is the recommended way:

console.log(
  firstDate,
  secondDate,
  firstDate.getTime() === secondDate.getTime()
);
IVO GELOV
  • 13,496
  • 1
  • 17
  • 26
1

What you are doing here is comparing two different instances (two different references) of Date object, which lead to an unexpected result

You could try to compare the millisecond of these by using getTime

const date = "28.02.2022";
const meeting = { date: "2022-02-28 14:30:00" }

const firstDate = new Date(`${date.split(".").reverse().join("-")}`);
const secondDate = new Date(`${meeting.date.split(" ")[0]}`)

firstDate.setHours(0,0,0,0);
secondDate.setHours(0,0,0,0);

console.log(firstDate, secondDate, firstDate.getTime() === secondDate.getTime());
hgb123
  • 13,869
  • 3
  • 20
  • 38
0

You can use .getTime() method to convert both of the dates to the number of milliseconds since the ECMAScript epoch and then compare them.

firstDate.setHours(0,0,0,0).getTime();
secondDate.setHours(0,0,0,0).getTime();
console.log(firstDate, secondDate, firstDate === secondDate);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Jalal
  • 334
  • 1
  • 4
  • 16