Compare two dates with JavaScript

Compare two dates in JavasSript; Through this tutorial, i am going to show you how to compare two dates in javascript with different formats.

Compare two dates in JavaScript

  • Compare two date without time in JavaScript
  • Compare date with current date in javascript
  • Javascript compare dates with time
  • Javascript compare two dates with time

Compare two dates without time in JavaScript

Using the following code, you can compare two dates without time:

   var date1 = new Date('2019-06-27');
   var date2 = new Date('2019-05-25');
    if(date1>date2){
      document.write('date1>date2');
    } else if(date1<date2) {
       document.write('date1<date2');
    }
    else{
      document.write('false');
    }

Compare date with current date in javascript

Using the compare date with the current date in JavaScript; as follows:

    var currentDate = new Date();
    var date = new Date('2019-12-28');
    if(currentDate>date){
      document.write('currentDate > date');
    }else if(currentDate<date) {
       document.write('currentDate < date');
    }
    else{
      document.write('currentDate==date');
    }

JavaScript compare dates with time

Using the following code, you can compare two dates with time; as follows:

    var date1 = new Date( "Dec 18, 2019 20:40:45" );
    var date2 = new Date( "Nov 15, 2018 21:35:40" );
    if(date1>date2){
      document.write('date1 > date2');
    }else if(date1<date2) {
       document.write(' date1 < date2 ');
    }
    else{
      document.write(' date1 == date2 ');
    }

JavaScript compare two dates with time

Using the following code, you can compare two dates using the getTime() method; as follows:

      var d1 = new Date( " Wed Nov 26 2019 09:52:06 " ); 
      var d2 = new Date(); 
      document.write("date 1 is :- " + d1); 
      document.write("<br>"); 
      document.write("date 2 is :- " + d2); 
      document.write("<br>"); 
      if (d1.getTime() === d2.getTime()) 
          document.write("Both  are equal"); 
      else
          document.write("Not equal"); 

More JavaScript Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.