How to Check if Date is Between Two Dates in Javascript

 

In this tutorial, you will learn how to check if a date is between two dates in javascript.  We are going to achieve this by using the Date constructor since we are dealing with dates here.

In the following example, we have 3 dates 01/01/2020, 01/15/2020, and 01/02/2020.  I simply want to verify if 01/02/2020 is between 01/01/2020 and 01/15/2020 or not. After completing the check, I want to 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.
  • The inner text for the button element is “Check” and for the h1 element is “Result”.
  • 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 3 global variables date1, date2, and date3. They hold 3 dates 01/01/2020, 01/15/2020, and 01/02/2020 respectively.  We are using the Date constructor to get the Date object for all 3 dates.
  • 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 for all 3 dates and assigning the return value to ms1, ms2, and ms3.
  • We are simply checking if ms3 is between ms1 and ms2 by using this piece of code ms3 > ms1 && ms3 < ms2 and displaying the result inside the h1 element.
let btnCheck = document.querySelector('button');

let result = document.querySelector('h1');

let date1 = new Date('01/01/2020');
let date2 = new Date('01/15/2020');
let date3 = new Date('01/02/2020');

btnCheck.addEventListener('click', () => {
    let ms1 = date1.getTime();
    let ms2 = date2.getTime();
    let ms3 = date3.getTime();

    result.innerText = ms3 > ms1 && ms3 < ms2;
});