Calculating the minutes between two dates in JavaScript involves finding the difference between their timestamps and converting the resulting milliseconds into minutes.
- Create Date objects for both dates.
- Subtract the earlier date from the later date to get the difference in milliseconds.
- Divide the milliseconds by 1000 * 60 to convert the difference into minutes.
Approach: Using Date Difference and Milliseconds
JavaScript stores dates internally as timestamps in milliseconds. By subtracting two Date objects, we get the difference in milliseconds. Dividing this value by 1000 converts it to seconds, and dividing by 60 converts it to minutes.
Example 1: In this example, the current date and New Year's date are used to calculate the difference in minutes.
// Declare dates
let today = new Date();
let newYear = new Date("01-01-2024");
// Display the dates
console.log("Today's Date: " + today.toLocaleDateString()
+ "\nNew Year's Date: " + newYear.toLocaleDateString());
// Calculate difference between two dates in minutes
let dif = newYear - today;
dif = Math.round(dif / (1000 * 60));
console.log("Minutes left: " + dif);
Example 2: In this example, the difference in minutes between January 1, 2019 and January 1, 2020 is calculated.
// Declare dates
let newYear1 = new Date("01-01-2019");
let newYear2 = new Date("01-01-2020");
// Display the dates
console.log("First Date: " + newYear1.toLocaleDateString()
+ "\nSecond Date: " + newYear2.toLocaleDateString());
// Calculate difference between two dates in minutes
let dif = newYear2 - newYear1;
dif = Math.round(dif / (1000 * 60));
console.log("Minutes left: " + dif);
Output
First Date: 1/1/2019 Second Date: 1/1/2020 Minutes left: 525600