Calculate Date Difference in JavaScript

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 days) between two given dates using JavaScript. We will use the Date object and write a function that subtracts the initial date from the final date and divides the result by the number of milliseconds in a day. This lab will help you understand how to work with dates in JavaScript and perform date calculations efficiently.


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-28235{{"`Calculate Date Difference in JavaScript`"}} javascript/data_types -.-> lab-28235{{"`Calculate Date Difference in JavaScript`"}} javascript/arith_ops -.-> lab-28235{{"`Calculate Date Difference in JavaScript`"}} javascript/comp_ops -.-> lab-28235{{"`Calculate Date Difference in JavaScript`"}} end

Function to Calculate Date Difference in Days

To calculate the difference between two dates in days, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the getDaysDiffBetweenDates function with two Date objects as arguments.
  3. The function will subtract the initial date from the final date and divide the result by the number of milliseconds in a day to get the difference in days between them.

Here's the code for the getDaysDiffBetweenDates function:

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24);

To use the function, pass in two Date objects in the format YYYY-MM-DD:

getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")); // 9

This will return the difference between the two dates in days, which is 9 in this example.

Summary

Congratulations! You have completed the Date Difference in Days lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like