The formatDistance
function from date-fns
is used to format the distance between two dates in a human-readable format. Here's an example of how to use it:
index.tsx207 chars9 lines
In the example above, we first import the formatDistance
function from the date-fns
library. We then create two Date
objects representing January 1st and April 1st of 2021. We then call the formatDistance
function with these two dates, which returns a string representing the distance between the two dates in a human-readable format. In this case, it returns "3 months".
You can also provide options to format the output. For example, to use short form distances (e.g. "3 mo." instead of "3 months"), you can provide the addSuffix
and short
options:
index.tsx247 chars12 lines
In this example, we pass an options object as the third argument to formatDistance
. This tells the function to add the suffix "ago" to the output and to use short form distances. The output in this case is "3 mo. ago".
gistlibby LogSnag