How to Check if Date is Less Than Current Date in Javascript

 
In this tutorial, you will learn how to check if a date is less than the current date in javascript. This can be easily achieved using the Date constructor.
 
In the following example, we have 2 dates, the current date and the hardcoded date 01/16/2020.  We will simply verify if 01/16/2020 is less than the current date and display a Boolean value on the screen.  Please have a look over the code example and steps given below.
 
HTML & CSS
  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>

    <div>
        <button>Check</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>    
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected 2 elements (button and h1) using the document.querySelector() method and stored them in btnCheck and result variables.
  • We have created 2 global variables, current and date. We are using the Date constructor to get the Date object.
  • We are getting the Date object for the current date and assigning it to the current variable. Similarly, we are getting the Date object for the 01/16/2020 date and assigning it to the date variable.
  • We have attached the click event listener to the button element.
  • In the Date object, we have the getTime() method which returns the date in milliseconds. We are calling this method on both variables and assigning values to ms1 and ms2.
  • We are simply comparing if ms2 is greater than ms1 and displaying the result inside the h1 element.
let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');

let current = new Date();
let date = new Date('01/16/2020');

btnCheck.addEventListener('click', () => {
    let ms1 = current.getTime();
    let ms2 = date.getTime();

    result.innerText = ms2 < ms1;
});
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •