You can compare two dates in JavaScript by subtracting one date from the other and checking the result. For example:

<pre class="wp-block-syntaxhighlighter-code"></pre>
var date1 = new Date("2022-01-01");
var date2 = new Date("2021-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 is the same as date2");
}

Alternatively, you can use the ‘getTime()’ method to get the number of milliseconds since January 1, 1970, and compare those values instead of the dates themselves.

<pre class="wp-block-syntaxhighlighter-code"></pre>
var date1 = new Date("2022-01-01").getTime();
var date2 = new Date("2021-01-01").getTime();
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 is the same as date2");
}

You can also use a library like moment.js which gives you a more human readable way to compare date and time.

const moment = require('moment');
const date1 = moment("2022-01-01");
const date2 = moment("2021-01-01");
if (date1.isAfter(date2)) {
  console.log("date1 is later than date2");
} else if (date1.isBefore(date2)) {
  console.log("date1 is earlier than date2");
} else {
  console.log("date1 is the same as date2");
}

Also Read:

Categorized in: