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

To use the formatRelative function from the date-fns library in TypeScript, you can follow these steps:

  1. First, you need to install the date-fns library and its associated types. You can do this by running the following command in your terminal:
index.ts
npm install date-fns @types/date-fns
37 chars
2 lines
  1. Once you have installed the library and its types, you can import the formatRelative function from the date-fns module in your TypeScript code as follows:
index.ts
import { formatRelative } from 'date-fns';
43 chars
2 lines
  1. The formatRelative function takes two arguments: a date argument (which can be a Date object or a date string in ISO format) and an optional options argument (which is an object of type LocaleOptions). You can use the function to format the input date as a relative time string (e.g. "5 days ago" or "in 3 months"). Here's an example usage:
index.ts
const inputDate = new Date(); // or use your own Date object
const formattedDate = formatRelative(inputDate, { locale: enUS }); // assuming you want to use the en-US locale
console.log(formattedDate); // "just now" or a similar relative time string
249 chars
4 lines

You can customize the options argument to use a different locale, provide a baseDate to calculate the relative time from, specify the unit of the time string (e.g. "week" or "day"), and more. Please refer to the date-fns documentation for more information on the available options.

gistlibby LogSnag