The formatRelative()
function is a part of the date-fns library and is used to format a date object as a human-readable string representing the relative time between the given date and the current date.
Here is an example of how to use the formatRelative()
function with date-fns:
index.tsx277 chars8 lines
In the example above, we first import the formatRelative()
function from the date-fns
library. We then create two Date
objects - currentDate
representing the current date and time, and someDateToFormat
representing the date and time we want to format. We finally call formatRelative()
passing in the someDateToFormat
and currentDate
object along with an optional object containing format options. The output of the function is a human-readable string representing the relative time between the two dates.
The formatRelative()
function also accepts a third optional options object, which allows you to customize the output format of the string. For example, you can customize the start of the week to be on Monday instead of Sunday by using the { weekStartsOn: 1 }
option as shown in the example above.
Note that if you want to format a date in a specific timezone using date-fns, you can use the zonedTimeToUtc()
and utcToZonedTime()
functions in combination with the formatRelative()
function.
gistlibby LogSnag