How to compare dates in Javascript?

by daisha.padberg , in category: JavaScript , 2 years ago

How to compare dates in Javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by janet.gerhold , a year ago

@daisha.padberg If you have a date as a string, you need to convert it to a Date() object in Javascript, and then you can easily compare dates in Javascript like this:


1
2
3
4
5
6
7
8
9
var now = new Date();
var yestarday = new Date(now.getDate() - 1);

// Output: false
console.log(now === yestarday);
// Output: true
console.log(now > yestarday);
// Output: false
console.log(now < yestarday);
by cameron.mccullough , a year ago

@daisha.padberg 

In JavaScript, you can compare dates using the built-in Date object and its methods. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let date1 = new Date("2022-01-01");
let date2 = new Date("2022-01-02");

if (date1 < date2) {
  console.log("date1 is less than date2");
} else if (date1 > date2) {
  console.log("date1 is greater than date2");
} else {
  console.log("date1 and date2 are equal");
}


In the example above, we create two Date objects, date1 and date2, and then compare them using the <, >, and === operators. If date1 is less than date2, we print "date1 is less than date2". If date1 is greater than date2, we print "date1 is greater than date2". If date1 and date2 are equal, we print "date1 and date2 are equal".


Note that when comparing dates, JavaScript compares the underlying timestamps, which are the number of milliseconds since January 1, 1970, 00:00:00 UTC. This means that if you create two Date objects using different time zones, they may not compare as expected. To avoid this, it's a good practice to use the UTC methods of the Date object, such as getUTCFullYear(), getUTCMonth(), getUTCDate(), etc., to get the UTC values of the date components.