July 3, 2020
How to Get Number of Days Between Two Dates in Javascript
- We have selected two elements
button
andh1
using thedocument.querySelector()
method and stored them inbtnGet
andresult
variables respectively. - We got instances of both dates using the
Date
constructor and stored them indate1
anddate2
variables. - We have attached the
click
event listener to thebutton
element. - Each
Date
instance has thegetTime()
method which returns the number of milliseconds. - Inside the
click
event handler function, we are using this method with both instances of date and subtracting the number of milliseconds returned bydate1
from the number of milliseconds returned bydate2
and storing the result in thediff
variable. - In one second, we have 1000 milliseconds. In one hour, we have 3600 seconds and in one day, we have 24 hours. Keeping this in mind, we are using this code
1000 * 3600 * 24
to get the number of milliseconds in a day and we are storing it in themsInDay
variable. - We need the difference in days, so we are simply dividing the number of milliseconds between two dates by the number of milliseconds in one day (
diff/msInDay
) and displaying the result in theh1
element.
let date1 = new Date('05/01/2019'); let date2 = new Date('09/09/2019'); let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); btnGet.addEventListener('click', () => { let diff = date2.getTime() - date1.getTime(); let msInDay = 1000 * 3600 * 24; result.innerText = diff/msInDay; });
In the following example, we have two dates 05/01/2019 and 09/09/2019. We will simply grab the number of days between these two dates using the
Date
constructor and display the result on the screen. Please have a look over the code example and steps given below.HTML & CSS
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements.button
element is“Get”
and for theh1
element is“Result”
.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript