How to get the number of days between two Dates in JavaScript?


In the given problem statement we will write a function to calculate the days between the given dates with the help of Javascript functionalities. For solving this problem we will use some built in method of Javascript and mathematical operations.

Understanding the problem statement

In the given problem we have to create a function to compute the number of days as outcome after calling the function by passing two dates. And this task can be done using Date object and basic math. For example if we have two dates like 2023-02-15 and 2023-02-25, so between these dates there are 10 days. So our purpose is to build a program to get this output.

Logic for the above problem

In the code we will create a new Date object for every input date and calculate the absolute difference between these dates and divide the difference by the number of milliseconds in a day. And then round the result to the nearest integer with the help of Math.round method.

Algorithm

Step1 − Create a function called numberOfDays which will take two dates as parameters.

Step2 − Define a constant oneDay which will represent the number of milliseconds in a day.

Step3 − Create two new dates with the help of Date objects based on the input dates.

Step4 − Calculate the difference between two given dates.

Step5 − After all the above steps, divide the difference by one day to get the difference in days.

Step6 − Round the result to the nearest integer using Math.round method.

Code for the algorithm

function numberOfDays(date1, date2) {
   // Number of milliseconds in a day
   const oneDay = 24 * 60 * 60 * 1000;
   const firstDate = new Date(date1);
   const secondDate = new Date(date2);
   const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
   return diffDays;
}
const date1 = '2021-04-15';
const date2 = '2021-06-10';
const numDays = numberOfDays(date1, date2);

console.log(`There are ${numDays} days between ${date1} and ${date2}`);

Complexity

The time taken for the above code is constant of O(1) as we have only performed fixed operations besides the size of the input dates. And the memory consumed by the algorithm is also O(1) because we have stored only a number of days in the code.

Conclusion

With this code we can effectively compute the number of days between the given dates in Javascript. And we have used a predefined object called Date and mathematical functions. And inside the function we have given two dates as parameters. The time and space complexity for the code is O(1), which is constant.

Updated on: 18-May-2023

673 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements