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

To use the sub function from the date-fns package in Javascript, first you need to install the package:

index.tsx
npm install date-fns
21 chars
2 lines

Then, you can import the function and use it to subtract a specified amount of time from a given date.

Here is an example of using the sub function to subtract 1 day from the current date:

index.tsx
const { sub } = require('date-fns');

const today = new Date();
const yesterday = sub(today, { days: 1 });

console.log(yesterday); // prints the date of the previous day
171 chars
7 lines

In this example, the sub function accepts two arguments - the date to be subtracted from and an object specifying the amount of time to subtract. The properties of this object should match the supported time units, such as days, hours, minutes, seconds, and so on.

In the code above, we are subtracting 1 day from the current date.

You can also subtract different combinations of time units by passing an object with multiple properties to sub:

index.tsx
const twoWeeksAgo = sub(new Date(), { weeks: 2, days: 1 });
console.log(twoWeeksAgo); // prints the date that is 2 weeks and 1 day before today
144 chars
3 lines

Note that the subtracted time is relative to the current date and time by default, but you can pass a second argument specifying the reference date - see the date-fns documentation for more information.

gistlibby LogSnag