Introduction
In this lab, we will explore how to calculate the difference in hours between two given dates using JavaScript. We will write a function that takes in two Date objects and returns the difference between them in hours. This lab will help you improve your JavaScript skills and give you a better understanding of date and time calculations in JavaScript.
JavaScript Function to Calculate Date Difference in Hours
To calculate the difference between two dates in hours using JavaScript, follow these steps:
Open the Terminal/SSH and type
nodeto start practicing coding.Use the following JavaScript function to get the difference (in hours) between two
Dateobjects:
const getHoursDiffBetweenDates = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 3600);
- Call the function with the two dates as arguments to get the difference in hours:
getHoursDiffBetweenDates(
new Date("2021-04-24 10:25:00"),
new Date("2021-04-25 10:25:00")
); // 24
Summary
Congratulations! You have completed the Date Difference in Hours lab. You can practice more labs in LabEx to improve your skills.