简体   繁体   中英

How to customize date-fns's formatRelative?

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

Although date-fns does not support a native method to do partial overwrites (yet), you can do the following, to do some manual tweaking (shown here by the german locale):

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 });

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 .

There is now a function named "formatRelative" available. Link to the docs: https://date-fns.org/v2.29.3/docs/formatRelative

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM