In a scenario, where the user can select a date ("from" date), along with the current date ("to" date), what is the best way to compare multiple (at least two) dates?
Assuming the incoming dates are a string with the format MM-DD-YYYY, consider the following comparison:
a = new Date("02-21-2018") // user "from" date
b = new Date() // current "to" date
b = b.setHours(0,0,0,0) // trim the time to compare just the dates
b = new Date(b) // converting back to the Date type
console.log("- :", a - b) // 0 (correct)
console.log("== :", a == b) // false (wrong)
console.log("<= :", a <= b) // true (correct)
console.log(">= :", a >= b) // true (correct)
console.log("value :", a.valueOf() == b.valueOf()) // true (correct)
Clearly there is a problem with comparing it directly using ==
. So what is the best alternative? Would anything be different if we have several (not just two) dates?
Also when comparing two dates like new Date("02-21-2018") <= new Date()
can a time zone affect the outcome?