How to Get Seconds 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 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;
});

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •