Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize date-fns's formatRelative?

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

like image 368
Hongbo Miao Avatar asked Nov 12 '17 00:11

Hongbo Miao


People also ask

Is date-fns good?

As you can see, Date-fns are well ahead in all 3 operations in terms of operations performed per second and size, and the simple API is the main reason behind this. Supports TypeScript and Flow. Always returns dates in the same time zone. Functional programming submodule makes the code clean and safe.

How can I get todays date in FNS?

const today = new Date(); console. log( lastDayOfMonth(today) ); That lastDayOfMonth method is one provided by date-fns, a self-proclaimed comprehensive toolset for manipulating JavaScript dates in the browser and Node. js.

What does new Date () return?

Return value Calling the Date() function (without the new keyword) returns a string representation of the current date and time, exactly as new Date().toString() does.


1 Answers

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 });
like image 194
spaceemotion Avatar answered Oct 05 '22 02:10

spaceemotion