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, 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, it 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 selected 2 elements (button and h1) using the document.querySelector() method and stored them in btnCheck and result variables respectively.
We have attached a click event listener to the button element.
We have 2 hardcode dates in date1 and date2 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” as innerText of the h1 element.
let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');
let date1 = new Date('2019', '10', '12', '10', '53','40');
let date2 = new Date('2019', '11', '12', '10', '53','40');
result.innerText = date1.getTime() === date2.getTime() ? 'Equal' : 'Not Equal';