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.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

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.