javascript

Javascript to get the number of days between two dates

Here, we are going to explain the methods and functions that can be used to get the number of days between two given dates.

const date_a = new Date("09/18/2021");
const date_b = new Date("10/20/2021");

const delta = date_b.getTime() - date_a.getTime();

const num_of_days = delta / (1000 * 60 * 60 * 24);

console.log("Number of days: " + num_of_days);

Output

Number of days: 32

Live demo of the above code

const date_1  = '2021-02-06';
const date_2    = '2021-03-19';

const num_of_days = moment(date_2).diff(moment(date_1), 'days');
If you are using the moment.js in your project then you can use it to calculate the number of days between two dates. The above code example shows the functionality where we are using the moment() function and the diff() function to find the number of days between the dates.
Was this helpful?