7

瞬间,使用日历,我可以自定义如何显示时间,如下所示

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

在 date-fns 中,基于formatRelative,我可以提供options.

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

但是,在阅读options文档后,我仍然无法弄清楚如何自定义它。

任何指南都会有所帮助。谢谢

4

2 回答 2

11

虽然 date-fns 不支持本地方法来进行部分覆盖(目前),但您可以执行以下操作来进行一些手动调整(此处显示为德语语言环境):

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 });
于 2018-03-06T20:52:27.063 回答
6

已接受答案的更新:在最新版本中date-fns,格式字符串看起来略有不同(单引号而不是大括号):

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

另请参阅中指定的格式字符串的此示例date-fns

于 2020-04-24T13:21:07.167 回答