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

To use the addYears function from date-fns in JavaScript, you will need to first install the library by running the following command:

npm install date-fns
21 chars
2 lines

Once installed, you can use the addYears function by importing it from the date-fns library and passing it a date and the number of years to add. Here's an example:

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

const date = new Date();
const newDate = addYears(date, 5);

console.log(newDate); // Output: 5 years from the current date
162 chars
7 lines

In this example, we first import the addYears function from the date-fns library. We then create a new date object using the Date constructor. Finally, we call the addYears function and pass in the date object and the number of years to add.

The addYears function returns a new Date object that represents the original date with the specified number of years added. The original date object is not modified.

Note that addYears can also handle negative values for subtracting years from a date.

gistlibby LogSnag