r/learnjavascript • u/elediardo • May 11 '22
Comparing two dates in JavaScript is easier than you may think.
32
u/burkybang May 11 '22
FYI, the month you set is June not May because it’s 0 based.
1
7
May 11 '22
[removed] — view removed comment
9
u/Marshallo May 11 '22
For others reading, it's because the day and month value is a key to represent a string ('Tuesday' or 'June' for example) whereas the day of the month (11) has no text version so can be 1-based.
It makes it nicer to do this:
month = ['Jan', 'Feb', 'Mar', etc...][date.getMonth()]
2
u/shiningmatcha May 11 '22
How about using == instead of ===? I think this way JS will compare the values returned by date1.valueOf() and date2.valueOf().
3
u/Patient_Signature467 May 11 '22
Because you are not comparing values but reference. date1 has a different location (reference) in the memory as date 2 even though their values are the same. In the second example that returns true, you are comparing actual values.
Look up on youtube reference vs value in javascript, if you get a visual explanation it will be easier to understand.
0
May 11 '22
[deleted]
6
u/xroalx May 11 '22
Because there are other languages that allow such comparison, or allow operator overloading. JavaScript isn't one of them, but not everybody has to necessarily be aware of that.
For example, the C# equivalent of
DateisDateTime, which overrides the comparison operators, meaningnew DateTime() == new DateTime()won't be comparing different objects, it will in fact compare the date and time they represent.0
12
u/shuckster May 11 '22
You could use coercion to shortcut it:
As you can see, coercing to a number implicitly invokes
getTime().