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 badges2 Answers
Reset to default 15Although 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.