You cannot compare dates in javascript

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2021-02-28

I was getting the wrong answers when working with dates in JavaScript. I had the following code:

function checkDateInInterval(dateToCheck) {
  const startDate = new Date(2008, 10, 5)
  const endDate = new Date(2009, 6, 1)

  return dateToCheck > startDate && dateToCheck < endDate
}

To get this code to work I needed to realize that comparing dates does not work in JavaScript. See the following:

new Date(2008,10,5) < new Date(2008,10,5)
false

new Date(2008,10,5) > new Date(2008,10,5)
false

new Date(2008,10,5) == new Date(2008,10,5)
false // watch out - this makes no sense semantically

new Date(2008,10,5) >= new Date(2008,10,5)
true // double watch out - inconsistent with the above

What's the solution? Convert to time

new Date(2008,10,5).getTime() == new Date(2008,10,5).getTime()
false // watch out - this makes no sense semantically