How to Get Milliseconds Between Two Dates in Javascript

 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button>Get</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

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();
});

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •