In JavaScript, you can compare two dates using the comparison operators (<
, >
, <=
, >=
). Here's an example of how to compare two dates to determine which one is earlier or later:
const date1 = new Date('2022-01-01'); // Create the first date object
const date2 = new Date('2022-02-01'); // Create the second date object
if (date1 < date2) {
console.log('Date 1 is earlier than Date 2');
} else if (date1 > date2) {
console.log('Date 1 is later than Date 2');
} else {
console.log('Date 1 and Date 2 are the same');
}
In this example, the comparison is done using the <
operator. If date1
is earlier than date2
, it will print "Date 1 is earlier than Date 2". If date1
is later than date2
, it will print "Date 1 is later than Date 2". If both dates are the same, it will print "Date 1 and Date 2 are the same".
Note that new Date()
creates a date object based on the provided date string. You can use any valid date string or variables that hold date objects in the comparison.