0

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?

Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34

1 Answers1

0

You need to use the .getTime() method on your date objects.
Checking equality on the date objects doesn't work.

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
a = a.getTime();
b = b.getTime();

console.log("- :", a - b)
console.log("== :", a == b)
console.log("<= :", a <= b)
console.log(">= :", a >= b)
console.log("value :", a.valueOf() == b.valueOf())

Here is a similar subject:
Compare two dates with JavaScript

About the timezone,
I am not sure about what you want to do, but :
The method .getTimezoneOffset() can be used on your date objects to return their offsets.
As javascript runs in your browser on your computer, I guess the time zone of your new Date() will be affected by your "TimezoneOffset".

Takit Isy
  • 9,688
  • 3
  • 23
  • 47
  • any good methods for comparing multiple dates using this method? E.g. `a`, `b`, `c`, `d`, ... – Aleksey Solovey Feb 21 '18 at 12:25
  • If there are many dates to compare… What do you want to get as a result ? Something like the ordering number from the min to the max ? I guess we could do something with a `for loop` if we put the dates in an object or array. – Takit Isy Feb 21 '18 at 12:46