Date Difference in Hours

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28236{{"`Date Difference in Hours`"}} javascript/data_types -.-> lab-28236{{"`Date Difference in Hours`"}} javascript/arith_ops -.-> lab-28236{{"`Date Difference in Hours`"}} javascript/comp_ops -.-> lab-28236{{"`Date Difference in Hours`"}} end

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.

Other JavaScript Tutorials you may like