How to Get Number of Days Between Two Dates 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 diff 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 the msInDay 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 the h1 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;
});