Introduction
In this lab, we will explore how to calculate the difference between two dates in minutes using JavaScript. We will use the Date object and a simple mathematical formula to obtain the time difference. By the end of this lab, you will be able to implement this functionality into your own projects and applications.
Function to Calculate Date Difference in Minutes
To calculate the difference (in minutes) between two dates, use the following function:
const getMinutesDiffBetweenDates = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 60);
Simply subtract the two Date objects and divide by the number of milliseconds in a minute to get the difference (in minutes) between them.
Here's an example usage of the function:
getMinutesDiffBetweenDates(
new Date("2021-04-24 01:00:15"),
new Date("2021-04-24 02:00:15")
); // 60
To start practicing coding, open the Terminal/SSH and type node.
Summary
Congratulations! You have completed the Date Difference in Minutes lab. You can practice more labs in LabEx to improve your skills.