Find number of days between two dates in JS

Number of Days Between Two Dates in JavaScript

 

In JavaScript, taking dates as input and their manipulation can be done by creating Date() objects.

Example :

const d = new Date();

Here, the new Date() returns the current date and time.

Step 1 :

To find the difference between two dates, we need to take two dates as input.

This can be done by making two constants d1 and d2 and providing the input inside new Date() as given.

const d1 = new Date("2021-03-25");
const d2 = new Date("2021-03-31");

Step 2 :

We need to get the dates of the given input to find the difference between them.

This can be done by using getDate() function which will return the date of objects d1 and d2 as a number between 1-31.

const d1Date = d1.getDate();
const d2Date = d2.getDate();

Step 3 :

Hence the difference between d1Date and d2Date can be found by simply subtracting the two.

console.log(Math.abs(d1-d2));

Here, Math.abs() is used to make sure to return the number of days as non-negative number in case the difference is negative.

 

The final code should look something like this : 

const d1 = new Date("2021-03-25");
const d2 = new Date("2021-03-31");

const d1Date = d1.getDate();
const d2Date = d2.getDate();
console.log(d1)
console.log(d2)

console.log(Math.abs(d1Date-d2Date));

 

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top