Comparing Dates and times
If you want to compare between dates in JavaScript, you can compare them directly, like this:
const a = new Date(2019, 0, 27)
const b = new Date(2019, 0, 26)
console.log(b < a) // true
The above only works for non-equality comparisons (>
, >=
, <
or <=
).
You can’t compare two dates with ===
because a Date is a JavaScript object. You can’t compare two objects with ===
. (Refer back to the if/else lesson in Module 2 (JavaScript basics) if you need a refresher).
const a = new Date(2019, 0, 26)
const b = new Date(2019, 0, 26)
console.log(a === b) // false
If you want to check if two dates are exactly the same, you need to create your own function to compare them. One simple way is to compare timestamps.
const isSameTime = (time1, time2) => {
return time1.getTime() === time2.getTime()
}
const a = new Date(2019, 0, 26)
const b = new Date(2019, 0, 26)
console.log(a === b) // false
console.log(isSameTime(a, b)) // true
Note: isSameTime
uses getTime
, and getTime
returns a timestamp in milliseconds. This means, isSameTime
works better for comparing between two different times (not date).
If you want to check if two dates fall on the same day, the best way is to compare their year
, month
and date
values.
const isSameDay = (date1, date2) => {
return date1.getFullYear() === date2.getFullYear() &&
date1.getMonth() === date2.getMonth() &&
date1.getDate()=== date2.getDate()
}
const a = new Date(2019, 0, 26, 10) // 10am, 26 Jan, 2019
const b = new Date(2019, 0, 26, 12) // 12pm, 26 Jan, 2019
console.log(isSameDay(a, b)) // true