1

I tried to compare two date objects in angular 4 but it always returning false

below are my code snippet

CheckForHoliday(d: Date) {
  let simpleDate = new Date(d.getFullYear(), d.getMonth(), d.getDay());
  let hDate = new Date(2018, 9, 1);
  console.log(simpleDate + "==========" + hDate);
  console.log(hDate === simpleDate);

  return (hDate === simpleDate);
}

The output is as below

Mon Oct 01 2018 00:00:00 GMT+0530 (India Standard Time)==========Mon Oct 01 2018 00:00:00 GMT+0530 (India Standard Time)

false

Any Idea why it returning false when the printed values look same?

Prasad Parab
  • 437
  • 1
  • 7
  • 26

3 Answers3

1

You could do a date.getTime() and then compare the two numbers

mak15
  • 367
  • 2
  • 12
0

You should compare the dates in the date Objects. If you call the getDate() method on the date Objects you will get true.

hDate.getDate() === simpleDate.getDate() //=> returns true
  • 1
    That's incorrect. [`Date.getDate()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate) returns the day of the month. – Jeto Oct 19 '18 at 13:08
  • Indeed missed that, my bad, Date.toString() or Date.getTime() should do the trick; – Rob Rombouts Oct 19 '18 at 13:15
  • 2
    Yes or even better, `Date.getTime()` (no need to compare string representations when you can compare the inner timestamps). – Jeto Oct 19 '18 at 13:16
0

new Date will return an object and you cannot compare objects like that. Try converting both of them to string before comparing them.

Do it like this

CheckForHoliday(d: Date) {
  let simpleDate = new Date(d.getFullYear(), d.getMonth(), d.getDay());
  let hDate = new Date(2018, 9, 1);
  console.log(simpleDate + "==========" + hDate);
  console.log(hDate === simpleDate);

  return (hDate.toString() === simpleDate.toString());
}
Cata John
  • 1,371
  • 11
  • 19