How to calculate minutes between two dates in JavaScript ?
Given two dates and the task is to get the number of minutes between them using JavaScript.
Approach:
- Initialize both Date object.
- Subtract the older date from the new date. It will give the number of milliseconds from 1 January 1970.
- Convert milliseconds to minutes.
Example 1: This example uses the current date and the next new year date to get the difference of dates in minutes.
html
< body > < h1 style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP" > </ p > < button onClick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" > </ p > <!-- Script to calculate difference between two dates --> < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); // Declare dates var today = new Date(); var newYear = new Date("01-01-2023"); // Display the dates up.innerHTML = "Today's Date= "+ today.toLocaleDateString() + "< br > newYear's Date = " + newYear.toLocaleDateString(); // Function to calculate difference // between two dates function GFG_Fun() { var dif = (newYear - today); var dif = Math.round((dif/1000)/60); down.innerHTML = "Minutes left = " + dif; } </ script > </ body > |
Output:

Example 2: This example uses the 2019 newYear and 2020 newYear date to get the difference in minutes.
html
< body > < h1 style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP" > </ p > < button onClick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" > </ p > <!-- Script to calculate difference between two dates --> < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); // Declare dates var newYear1 = new Date("01-01-2019"); var newYear2 = new Date("01-01-2020"); // Display the dates up.innerHTML = "First Date= "+ newYear1.toLocaleDateString() + "< br > Second Date = " + newYear2.toLocaleDateString(); // Function to calculate difference // between two dates function GFG_Fun() { var dif = (newYear2 - newYear1); var dif = Math.round((dif/1000)/60); down.innerHTML = "Minutes left = " + dif; } </ script > </ body > |
Output:

Please Login to comment...