To use the formatDistanceToNowStrict()
function from the date-fns library in TypeScript, you first need to install the library via your preferred method (e.g. npm or yarn).
index.ts21 chars2 lines
Once you have date-fns installed, you can import the formatDistanceToNowStrict()
function like this:
index.ts54 chars2 lines
The formatDistanceToNowStrict()
function takes two arguments: a Date
object or a timestamp (in milliseconds), and an optional object containing formatting options.
Here's an example of using formatDistanceToNowStrict()
to format a date as a string:
index.ts152 chars5 lines
In the above example, we're passing a Date
object to formatDistanceToNowStrict()
, which will return the distance from that date to the current time in a human-readable format. Because we're using the Strict
version of the function, it will only use time units of "years", "months", "weeks", "days", "hours", "minutes", and "seconds" in its output.
You can also pass an object containing formatting options as a second argument to formatDistanceToNowStrict()
. For example, if you want to change the locale or add a suffix to the output, you can do something like this:
index.ts191 chars8 lines
In this example, we're passing both a Date
object and an options object to formatDistanceToNowStrict()
. We're using the fr
locale (which is French) and setting the addSuffix
option to true
, which will add the words "ago" or "in" to the output, depending on whether the date is in the past or future.
Hopefully, this helps you get started with using formatDistanceToNowStrict()
in TypeScript!
gistlibby LogSnag