简体   繁体   English

如何自定义date-fns的formatRelative?

[英]How to customize date-fns's formatRelative?

In moment, with calendar , I can customize how to show the time like below此刻,有了calendar ,我可以自定义如何显示时间,如下所示

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 .在 date-fns 中,基于formatRelative ,我可以提供options

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

However, after reading options document, I still cannot figure out how to customize it.但是,阅读options文档后,我仍然无法弄清楚如何自定义它。

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

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

Also see this example of the format string specified in the date-fns source .另请参阅date-fns源中指定的格式字符串示例

There is now a function named "formatRelative" available.现在有一个名为“formatRelative”的 function 可用。 Link to the docs: https://date-fns.org/v2.29.3/docs/formatRelative文档链接: https://date-fns.org/v2.29.3/docs/formatRelative

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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