avatar

Hassan khan

Last updated: March 22,2022

Compare dates in javascript

Javascript compare dates


In this article, you will learn how to compare two dates in JavaScript. Working with date and time is hard at the beginning, but as you gain experience it becomes fun.
We will compare two dates using the getTime() method of date, which converts and return the date into milliseconds.


Syntax:

1
2
3
4
5
6
7
8
9
10
11
12

    let d1 = new Date('2020-01-23').getTime();
    let d2 = new Date('2020-01-21').getTime(); 
  
    if (d1 < d2) {
        console.log(d1+' is less than '+d2);
    } else if (d1 > d2) {
        console.log(d1+' is greater than '+d2);
    } else {
        console.log('Both dates are equal');
    }
  

Share