July 2, 2020
How to Get Difference Between Two Dates in Hours 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 thems
variable. - In one second, we have 1000 milliseconds. In one minute, we have 60 seconds and in one hour, we have 60 minutes. Keeping this in mind, we are using this code
1000 * 60 * 60
to get the number of milliseconds in one hour and storing it in thehour
variable. - We need the difference in hours, so we are simply dividing the number of milliseconds between two dates by the number of milliseconds in one hour (
ms/hour
) and displaying the result in theh1
element.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); let date1 = new Date('01/01/2020'); let date2 = new Date('01/03/2020'); btnGet.addEventListener('click', () => { let ms = date2.getTime() - date1.getTime(); let hour = 1000 * 60 * 60; result.innerText = ms/hour; });
In the following example, we have two dates
01/01/2020
and01/03/2020
. We will simply grab the difference in the number of hours between these 2 dates using theDate
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.“Get”
and for the h1 element is“Result”
.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript