How to compare Date and Time in Javascript

Comparing Datetimes in Javascript

Comparing dates in javascript is pretty easy. If the date string has been created with Date object then the dates can be compared using equality operator. Namely <, >, =.

let d1 = new Date();
let d2 = new Date();

let equal = d1.getTime() === d2.getTime();
let notEqual = d1.getTime() !== d2.getTime();

console.log(equal, notEqual);

if (d1 > d2) {
  console.log('d1 is greater than d2');
} else if (d1 < d2) {
  console.log('d2 is greater than d1');
} else {
  console.log('d1 & d2 are equal);

Libraries to compare dates in Javascript

Moment.js is the most popular library for date comparison/manipulatoin in Javascript.

<script src="moment.js"></script>
    moment().add(8, 'days').subtract(5, 'months').year(2019).hours(3).minutes(6).seconds(9);

It makes common tasks very easy.