How to customize date-fns's formatRelative?

Viewed 7667

In moment, with calendar, I can customize how to show the time like below

moment(dateTime).calendar(null, {
    sameDay: '[Today]',
    nextDay: '[Tomorrow]',
    nextWeek: 'dddd',
    lastDay: '[Yesterday]',
    lastWeek: '[Last] dddd',
    sameElse: 'DD/MM/YYYY'
});

In date-fns, based on the formatRelative, I can provide options.

formatRelative(dateTime, Date.now(), options);

However, after reading options document, I still cannot figure out how to customize it.

Any guide will be helpful. Thanks

2 Answers

An update on the accepted answer: it looks like in the latest version of date-fns, the format strings look slightly different (single quotes instead of braces):

import { formatRelative } from 'date-fns';
import { de } from 'date-fns/esm/locale';

const formatRelativeLocale = {
  lastWeek: "'letzten' dddd 'um' LT",
  yesterday: "'gestern um' LT",
  today: "'heute um' LT",
  tomorrow: "'morgen um' LT",
  nextWeek: "dddd 'um' LT",
  other: 'L LT', // Difference: Add time to the date
};

const locale = {
  ...de,
  formatRelative: token => formatRelativeLocale[token],
};

const text = formatRelative(date, new Date(), { locale });

Also see this example of the format string specified in the date-fns source.

Related