Date-fns: Format relative without time

Created on 24 Jun 2019  路  3Comments  路  Source: date-fns/date-fns

Is it possible to relative format a date but without the time ?
I'd like to have just "tomorrow" or "today" and not the "tomorrow at".
Any idea?

Thanks

馃檹 Feature request

Most helpful comment

Example of a solution offered by @kossnocorp

import enGB from 'date-fns/locale/en-GB';
import formatRelative from 'date-fns/formatRelative';
import addDays from 'date-fns/addDays'

// https://date-fns.org/docs/I18n-Contribution-Guide#formatrelative
// https://github.com/date-fns/date-fns/blob/master/src/locale/en-US/_lib/formatRelative/index.js
// https://github.com/date-fns/date-fns/issues/1218
// https://stackoverflow.com/questions/47244216/how-to-customize-date-fnss-formatrelative
const formatRelativeLocale = {
  lastWeek: "'Last' eeee",
  yesterday: "'Yesterday'",
  today: "'Today'",
  tomorrow: "'Tomorrow'",
  nextWeek: "'Next' eeee",
  other: 'dd.MM.yyyy',
};

const locale = {
  ...enGB,
  formatRelative: (token) => formatRelativeLocale[token],
};

const tomorrow = addDays(new Date, 1)
console.log(formatRelative(tomorrow, new Date(), { locale })) // Tomorrow

All 3 comments

Maybe we could add an option for that, but that will require updating all of the locales, and that's a lot of work. I'm not sure if it's worth it because you can create a locale with custom formatRelative.

See: https://date-fns.org/v2.0.0-alpha.37/docs/I18n-Contribution-Guide#creating-a-locale-with-the-same-language-as-another-locale and: https://github.com/date-fns/date-fns/blob/master/src/locale/en-US/_lib/formatRelative/index.js

Yes, I ended up overriding the formatRelative for the locales I use to add a withoutTime option.
I was switching from luxon, and it's a feature I was missing.
Sure, it's a lot of work, but there is already everything necessary. We would just need to split the relative formats (at least for the locales I know).

Example of a solution offered by @kossnocorp

import enGB from 'date-fns/locale/en-GB';
import formatRelative from 'date-fns/formatRelative';
import addDays from 'date-fns/addDays'

// https://date-fns.org/docs/I18n-Contribution-Guide#formatrelative
// https://github.com/date-fns/date-fns/blob/master/src/locale/en-US/_lib/formatRelative/index.js
// https://github.com/date-fns/date-fns/issues/1218
// https://stackoverflow.com/questions/47244216/how-to-customize-date-fnss-formatrelative
const formatRelativeLocale = {
  lastWeek: "'Last' eeee",
  yesterday: "'Yesterday'",
  today: "'Today'",
  tomorrow: "'Tomorrow'",
  nextWeek: "'Next' eeee",
  other: 'dd.MM.yyyy',
};

const locale = {
  ...enGB,
  formatRelative: (token) => formatRelativeLocale[token],
};

const tomorrow = addDays(new Date, 1)
console.log(formatRelative(tomorrow, new Date(), { locale })) // Tomorrow
Was this page helpful?
0 / 5 - 0 ratings