How to Get Seconds Between Two Dates in Javascript

In this tutorial, you will learn how to get seconds between two dates in javascript. We have 86400 seconds in a single day which is equivalent to 1.2442e+11 milliseconds.
  • We have selected button and h1 elements 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.
  • We need the number of seconds, so we are simply dividing milliseconds by 1000 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 second = 1000;
    
    result.innerText = ms/second;
});