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

To use the addMonths function from the date-fns library in TypeScript, you need to install date-fns and its corresponding types package:

index.ts
npm install date-fns
npm install @types/date-fns
49 chars
3 lines

Then in your TypeScript file, you can import addMonths and use it as follows:

index.ts
import addMonths from 'date-fns/addMonths';

const originalDate = new Date('2022-05-25');
const numberOfMonthsToAdd = 3;
const newDate = addMonths(originalDate, numberOfMonthsToAdd);

console.log(newDate);
// Output: Sat Aug 25 2022 00:00:00 GMT-0500 (Central Daylight Time)
275 chars
9 lines

In the example above, we imported the addMonths function from date-fns/addMonths. We then defined a Date object representing our original date, and the number of months we want to add to that date. Finally, we passed these two values to addMonths to get a new Date object representing the new date with the desired number of months added.

gistlibby LogSnag