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

To use the differenceInMinutes function from date-fns library in JavaScript, you must first install and import the date-fns package in your project.

You can install the package using npm by running the following command:

npm install date-fns
21 chars
2 lines

Once installed, you can import the function in your JavaScript file as follows:

index.tsx
import { differenceInMinutes } from 'date-fns';
48 chars
2 lines

The differenceInMinutes function calculates the difference in minutes between two dates or timestamps. It accepts two arguments - the first argument is the date or timestamp to subtract from, and the second argument is the date or timestamp to subtract.

Here's an example code snippet that demonstrates how to use the differenceInMinutes function:

index.tsx
import { differenceInMinutes } from 'date-fns';

const start = new Date(2021, 9, 1, 12, 0);
const end = new Date(2021, 9, 1, 14, 30);

const minutesDiff = differenceInMinutes(end, start);

console.log(`The difference in minutes between ${start} and ${end} is ${minutesDiff}.`)
277 chars
9 lines

Output:

index.tsx
The difference in minutes between Wed Oct 01 2021 12:00:00 GMT+0530 (India Standard Time) and Wed Oct 01 2021 14:30:00 GMT+0530 (India Standard Time) is 150.
158 chars
2 lines

In the above code, we first created two date objects, representing the start and end times of an event. We then passed these dates to the differenceInMinutes function to calculate the difference in minutes between them. The result is stored in the variable minutesDiff. Finally, we logged the result to the console.

gistlibby LogSnag