How to Compare Two Dates in Javascript
In this tutorial, you will learn how to compare two dates in javascript. Date comparison can be easily done in javascript using the Date
constructor. Your question would be here why or when do you need to do a date comparison?
Suppose you are a developer who manages an eCommerce store. Each product in your store has a specific expiry date and you want to make sure that expired products do not show up on your store. In such a scenario, you can simply do the comparison between the current date and expiry date and toggle the products visibility.
We will perform a basic date equality check using the getTime()
method which returns the number of milliseconds between midnight of January 1, 1970, and the specified date.
In the following example, we have 2 hardcoded dates, Nov 12 2019 10:53:40
, and Dec 12 2019 10:53:40
. We will simply check if they are equal or not and display the result 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, it 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 class="container"> <button>Check</button> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
.container { display: flex; flex-direction: column; align-items: center; justify-content: space-between; height: 70px; }
Javascript
- We have selected 2 elements (
button
andh1
) using thedocument.querySelector()
method and stored them inbtnCheck
andresult
variables respectively. - We have attached a
click
event listener to thebutton
element. - We have 2 hardcode dates in
date1
anddate2
variables. - We are using
console.log()
to log dates in the console window. - We are using the
getTime()
method to get dates in milliseconds and then we are comparing them using a strict equality operator. Depending upon the result of the comparison, we are setting“Equal”
or“Not Equal”
asinnerText
of theh1
element.
let btnCheck = document.querySelector('button'); let result = document.querySelector('h1'); btnCheck.addEventListener('click',() =>{ let date1 = new Date('2019', '10', '12', '10', '53','40'); let date2 = new Date('2019', '11', '12', '10', '53','40'); console.log(date1); console.log(date1.getTime()); console.log(date2); console.log(date2.getTime()); result.innerText = date1.getTime() === date2.getTime() ? 'Equal' : 'Not Equal'; });