July 2, 2020
How to Get Difference Between Two Dates in Minutes in Javascript
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
, andh1
). Thediv
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 thehead
element. - We have also included our javascript file
script.js
with ascript
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
andh1
using thedocument.querySelector()
method and stored them inbtnGet
andresult
variables respectively. - We got instances of both dates using the
Date
constructor and stored them indate1
anddate2
variables. - We have attached the
click
event listener to thebutton
element. - Each
Date
instance has thegetTime()
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 bydate1
from the number of milliseconds returned bydate2
and storing the result in thems
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 theh1
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; });