Ben
Ben

Reputation: 16689

FormatDistance without "hours ago"

When using date-fns, how can I use intlFormatDistance such that for a duration less than 24 hours, it displays "today" or "yesterday", instead of "x hours ago".

Example:

intlFormatDistance(myDate, new Date());
// Default output: 13 hours ago
// Desired output: Today

Upvotes: -1

Views: 28

Answers (1)

mplungjan
mplungjan

Reputation: 178375

Wrap it

const customIntlFormatDistance = (date, baseDate = new Date()) => 
  differenceInHours(baseDate, date) < 24 ? "Today" :
    isYesterday(date) ? "Yesterday" : 
      intlFormatDistance(date, baseDate);

In case you meant "if today" instead of < 24 then:

const customIntlFormatDistance = (date, baseDate = new Date()) => 
  isToday(date) ? "Today" : 
    isYesterday(date) ? "Yesterday" : 
      intlFormatDistance(date, baseDate);

Upvotes: 0

Related Questions