how to use the formatdistancetonowstrict function from the date-fns library in typescript

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.ts
npm install date-fns
21 chars
2 lines

Once you have date-fns installed, you can import the formatDistanceToNowStrict() function like this:

index.ts
import { formatDistanceToNowStrict } from 'date-fns';
54 chars
2 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.ts
const distance = formatDistanceToNowStrict(new Date('2022-02-28T12:00:00'));
// Output: "in 1 year"

console.log(`The event is happening ${distance}`);
152 chars
5 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.ts
const distance = formatDistanceToNowStrict(new Date('2022-02-28T12:00:00'), {
  addSuffix: true,
  locale: fr,
});
// Output: "dans 1 an"

console.log(`L'événement se produira ${distance}`);
191 chars
8 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