How to Get Difference Between Two Dates in Hours in Javascript

 
  • We have selected two elements button and h1 using the document.querySelector() method and stored them in btnGet and result variables respectively.
  • We got instances of both dates using the Date constructor and stored them in date1 and date2 variables.
  • We have attached the click event listener to the button element.
  • Each Date instance has the getTime() 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 by date1 from the number of milliseconds returned by date2 and storing the result in the ms 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 the hour 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 the h1 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;
});