July 1, 2020
How to Check if Date is Less Than Current Date in Javascript
- We have 3 elements in the HTML file (
div
,button
, andh1
). Thediv
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 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 2 global variables,
current
anddate
. We are using theDate
constructor to get theDate
object. - We are getting the
Date
object for the current date and assigning it to thecurrent
variable. Similarly, we are getting theDate
object for the01/16/2020
date and assigning it to thedate
variable. - 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 on both variables and assigning values toms1
andms2
. - We are simply comparing if
ms2
is greater thanms1
and displaying the result inside theh1
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; });