Date comparison in Javascript

cover-photo

Date comparison in Javascript


blog-photo


In this post we are going to learn how to compare two date in javascript. The most simplest way of javascript date comparison is to convert them to time. Lets us take below example.


Javascript Date Comparison

var date1 = new Date();
var date2 = new Date();

if (date1.getTime() === date2.getTime()) { // 1605815698393 === 1605815698393 
    console.log("Dates are equal");
}
else {
    console.log("Dates are Not equal");
}

Here we have used Date() method which will assign the current date as date Objects to variables date1 and date2 respectively and getTime() method which returns the numeric value corresponding to the time for the specified date according to universal time. The getTime() method returns the number of milliseconds. This helps to compare both dates with time.

Lets us take another example to compare two different dates.

var date3 = new Date('1995-12-17T03:24:00');
// Sun Dec 17 1995 03:24:00 GMT...

if (date1.getTime() === date3.getTime()) {  // 1605815698393 === 819150840000
    console.log("Dates are equal");
}
else {
    console.log("Dates are Not equal");
}

In this both examples we compared whether the dates were equal or not similarly we can compare and check which date is greater or smaller by using respective Comparison Operators (>, <, >=, <=).


Happy Coding!