How to compare dates in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Dates can be compared easily in javascript. The dates can belong to any frame i.e past, present and future. Past dates can be compared to future or future dates can be compared to the present. 

Example-1

In the following example, a date in the year 2000 is compared with today's date and the respective message is displayed in the output. 

Live Demo

<html>
<body>
   <p id="compare"></p>
<script>
   var today = new Date();
   var otherday = new Date();
   otherday.setFullYear(2000, 2, 14);
   if (otherday > today) {
      var msg = "The date you provided is a future date ";
   } else {
             var msg = "The date you provided is a past date";
   }
   document.getElementById("compare").innerHTML = msg;
</script>
</body>
</html>

Output

The date you provided is a past date

Example-2

In the following example, a date in the year 2900 is compared with today's date and the respective message is displayed in the output. 

Live Demo

<html>
<body>
   <p id="compare"> </p>
<script>
   var today = new Date();
   var otherday = new Date();
   otherday.setFullYear(2900, 2, 14);
   if (otherday > today) {
      var msg = "The date you provided is a future date ";
   } else {
             var msg = "The date you provided is a past date";
   }
   document.getElementById("compare").innerHTML = msg;
</script>
</body>
</html>

Output

The date you provided is a future date
raja
Published on 15-Jul-2019 12:18:42
Advertisements