How to Get Milliseconds Between Two Dates in Javascript

  • We have selected 2 elements (button and h1) using the document.querySelector() method and stored them in btn and result variables.
  • Using the Date constructor, we created 2 Date objects date1 and date2 of dates 01/10/2020 and 01/20/2020 respectively.
  • We have attached a click event listener to the button element.
  • Date object has getTime() method which returns the date in milliseconds. We are simply subtracting date2 from date1 and displaying the result inside h1 element.
let btnGet = document.querySelector('button');
let result = document.querySelector('h1');

let date1 = new Date('01/10/2020');
let date2 = new Date('01/20/2020');

btnGet.addEventListener('click', () => {
    result.innerText = date2.getTime() - date1.getTime();