JavaScript(JS) JS compare the value of two dates
In JavaScript, you can compare the value of two dates using the comparison operators >
(greater than), <
(less than), >=
(greater than or equal to), and <=
(less than or equal to). Here's an example:
const date1 = new Date('2022-01-01'); const date2 = new Date('2023-01-01'); if (date1 > date2) { console.log('date1 is later than date2'); } else if (date1 < date2) { console.log('date1 is earlier than date2'); } else { console.log('date1 and date2 are the same'); }
In the above example, we declare two Date
objects date1
and date2
with different values. We then use the comparison operators to compare the value of the two dates.
If date1
is later than date2
, the code inside the first if
block will execute. If date1
is earlier than date2
, the code inside the else if
block will execute. If date1
and date2
have the same value, the code inside the else
block will execute.
Note that when comparing dates in JavaScript, the values of the dates are compared, which are the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. If you are comparing dates in a specific time zone or locale, you would need to adjust the dates accordingly.