最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to customize date-fns's formatRelative? - Stack Overflow

programmeradmin8浏览0评论

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

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

Share Improve this question edited Nov 12, 2017 at 1:54 Hongbo Miao asked Nov 12, 2017 at 0:18 Hongbo MiaoHongbo Miao 49.9k67 gold badges198 silver badges319 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 15

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.

发布评论

评论列表(0)

  1. 暂无评论