Date Difference in Hours

Beginner

This tutorial is from open-source community. Access the source code

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:

  1. Open the Terminal/SSH and type node to start practicing coding.

  2. Use the following JavaScript function to get the difference (in hours) between two Date objects:

const getHoursDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600);
  1. 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.