how to use the differenceindays function from date-fns in javascript

date-fns is a popular library in JavaScript used to work with dates. differenceInDays is a date-fns function that returns the difference in days between two provided dates. Here is an example of how to use differenceInDays function:

index.tsx
const differenceInDays = require('date-fns/differenceInDays');

const date1 = new Date("2021-01-01");
const date2 = new Date("2021-01-05");

const diffDays = differenceInDays(date2, date1);

console.log(diffDays); // Output: 4
227 chars
9 lines

In the above example, we required the differenceInDays function from the date-fns library. We passed two dates date1 and date2 to the differenceInDays function. The function returned the difference in days between date2 and date1, and we stored the returned value in the diffDays variable. Finally, we logged the diffDays variable value to the console.

Note that differenceInDays function returns the difference in integer, so in the above example, it returned 4 as the difference between 2021-01-01 and 2021-01-05 is 4 days.

gistlibby LogSnag