To use formatDistance
from date-fns
, first, we need to install date-fns
as a dependency in our project:
21 chars2 lines
Then, we can import formatDistance
from date-fns
:
index.tsx43 chars2 lines
formatDistance
function accepts two arguments: start date and end date. It returns a string representing the distance between them.
Here's an example that calculates the distance between two dates:
index.tsx180 chars8 lines
In this example, we pass the two dates: startDate
and endDate
. The formatDistance
function calculates the time difference between them and returns a string that represents the distance (in this case, "4 months").
We can also provide a third argument, options
, to customize the output:
index.tsx173 chars10 lines
In this updated example, we pass a third argument, options
, with two properties: addSuffix
and includeSeconds
. With addSuffix
set to true
, the output includes the suffix "in" or "ago". With includeSeconds
set to true
, the output includes the seconds.
gistlibby LogSnag