how to use the sub function from the date-fns library in typescript

To use the sub function from the date-fns library in TypeScript, you'll first need to import it like this:

index.ts
import { sub } from 'date-fns';
32 chars
2 lines

The sub function accepts two arguments: a date (either a Date instance or a string that can be converted to a Date) and an object that specifies the amount of time to subtract from the date. Here's an example of how you could use it:

index.ts
const myDate = new Date('2021-09-06T15:23:45');
const subtractedDate = sub(myDate, {
  days: 3,
  hours: 6,
  minutes: 30,
});
127 chars
7 lines

In this example, myDate represents a date and time (September 6th, 2021 at 3:23:45 PM). We're then using the sub function to subtract 3 days, 6 hours, and 30 minutes from that date. The resulting subtractedDate will be a new Date instance representing September 3rd, 2021 at 8:53:45 AM.

You can adjust the object passed as a parameter to subtract different amounts of time, such as only hours or minutes if you prefer. The sub function returns a new Date instance that represents the resulting date and time after the subtraction.

gistlibby LogSnag