如何自定义date-fns的formatRelative?

时间:2017-11-12 00:18:54

标签: javascript datetime date-fns

暂时,使用calendar,我可以自定义如何显示时间

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文档后,我仍然无法弄清楚如何自定义它。

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

已接受答案的更新:在最新版本的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 });

另请参阅this example of the format string specified in the date-fns source