How to Get Difference Between Two Dates in Minutes in Javascript

 

In this tutorial, you will learn how to get the difference between two dates in minutes in javascript. We have 1440 minutes in a single day which is equivalent to 1.2442e+11 milliseconds.

In the following example, we have two dates 01/10/2020 and 01/12/2020.  We will simply grab the difference in the number of minutes between these two dates using the Date constructor and display the result on the screen. Please have a look over the code example and steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Get” and for the h1 element is “Result”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!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 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 ms variable.
  • In one second, we have 1000 milliseconds and in one minute, we have 60 seconds. Keeping this in mind, we are using this code 1000 * 60 to get the number of milliseconds in minutes and we are storing it in the minute variable.
  • We need the difference in minutes, so we are simply dividing the number of milliseconds between two dates by the number of milliseconds in one minute (ms/minute) and displaying the result in the h1 element.
let btnGet = document.querySelector('button');

let result = document.querySelector('h1');

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

btnGet.addEventListener('click', () => {
    let ms = date2.getTime() - date1.getTime();
    let minute = 1000 * 60;
    
    result.innerText = ms/minute;
});