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

To use the differenceInYears function from the date-fns library in TypeScript, you'll need to install the library and include the import statement at the top of your TypeScript file:

index.ts
import { differenceInYears } from 'date-fns';
46 chars
2 lines

Then, you can call the differenceInYears function with two Date objects as arguments, like this:

index.ts
const date1 = new Date('2000-01-01');
const date2 = new Date('2021-08-06');

const yearsDifference = differenceInYears(date2, date1);

console.log(yearsDifference); // Output: 21
179 chars
7 lines

In the code above, we first create two JavaScript Date objects representing two different dates. We then call the differenceInYears function with the two dates, which returns the difference in years between them. We store the result of this function call in the yearsDifference variable, and then log it to the console.

gistlibby LogSnag