Computer >> Computer tutorials >  >> Programming >> Javascript

How to compare two dates with JavaScript?


To compare two dates with JavaScript, create two dates object and get the recent date. You can try to run the following code to compare two dates.

Example

<!DOCTYPE html>
<html>
   <body>
      <script>
         var date1, date2;
         date1 = new Date();
         document.write(date1);
         date2 = new Date( "Dec 15, 2014 21:20:15" );
         document.write("<br>"+date2);
         if (date1 > date2) {
            document.write("<br>Date1 is the recent date.");
         } else {
            document.write("<br>Date 2 is the recent date.");
         }
      </script>
   </body>
</html>

Output

Sat Dec 15 2018 11:08:06 GMT+0530 (India Standard Time)
Mon Dec 15 2014 21:20:15 GMT+0530 (India Standard Time)
Date1 is the recent date.