How to Get Milliseconds Between Two Dates in Javascript

In this tutorial, you will learn how to get milliseconds between two dates in javascript. Millisecond is one-thousandth of a second. Getting a difference in milliseconds between 2 dates is very easy to be achieved using the Date constructor 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();
});