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

To use the subyears function from date-fns library in Javascript, you need to first install the library through npm:

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

Once installed, you can import and use the subYears function as follows:

index.tsx
// Import the subYears function
import { subYears } from 'date-fns';

// Usage example: subtract 1 year from March 1, 2022
const someDate = new Date(2022, 2, 1); // JS Date month starts at 0, March is month 2
const oneYearAgo = subYears(someDate, 1);

console.log(oneYearAgo); // Output: Mon Mar 01 2021 00:00:00 GMT-0800 (Pacific Standard Time)
346 chars
9 lines

The subYears function takes two parameters:

  • date: a Date object representing the date you want to subtract years from
  • years: the number of years you want to subtract

In the example above, we subtracted 1 year from someDate, which resulted in a new Date object representing March 1, 2021.

gistlibby LogSnag