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) // trueThe 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) // falseIf 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.
function 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) // falseconsole.log(isSameTime(a, b)) // trueNote: 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.
function 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, 2019const b = new Date(2019, 0, 26, 12) // 12pm, 26 Jan, 2019console.log(isSameDay(a, b)) // trueWelcome! Unfortunately, you donβt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson