The differenceInYears
function from the date-fns
library is used to get the difference between two dates in years. Here's how to use it:
First, you need to install the date-fns
library. You can do this using npm by running the following command in your terminal:
index.tsx21 chars2 lines
Once you've installed the library, you can import the differenceInYears
function in your javascript file like this:
index.tsx51 chars2 lines
Alternatively, you can use the ES6 import statement like this:
index.tsx46 chars2 lines
Now you're ready to use the differenceInYears
function. Here's the basic syntax:
index.tsx151 chars7 lines
In this example, we create two date objects, start
and end
, and then pass them to the differenceInYears
function. The function returns the number of years between the two dates, which we store in the years
variable.
The output of the console.log statement is 10
, which is the number of years between 2010 and 2020.
Note that the differenceInYears
function rounds down to the nearest whole number of years. So if the difference between two dates is 11 months and 29 days
, it will still return 0
years.
gistlibby LogSnag