July 1, 2020
How to Check if Date is Between Two Dates in Javascript
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
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The inner text for the
button
element is “Check” and for theh1
element is “Result”. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
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
andh1
) using thedocument.querySelector()
method and stored them inbtnCheck
andresult
variables. - We have created 3 global variables
date1
,date2
, anddate3
. They hold 3 dates01/01/2020
,01/15/2020
, and01/02/2020
respectively. We are using theDate
constructor to get theDate
object for all 3 dates. - We have attached the
click
event listener to thebutton
element. - In the
Date
object, we have thegetTime()
method which returns the date in milliseconds. We are calling this method for all 3 dates and assigning the return value toms1
,ms2
, andms3
. - We are simply checking if
ms3
is betweenms1
andms2
by using this piece of codems3 > ms1 && ms3 < ms2
and displaying the result inside theh1
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; });