From 20f3b5c794fd54827e24926dcae186fdfb1042c6 Mon Sep 17 00:00:00 2001 From: Noah Saso Date: Wed, 20 Nov 2024 11:48:15 -0800 Subject: [PATCH] improve time ago granularity --- .../hooks/useTranslatedTimeDeltaFormatter.ts | 40 +++++++++++++++---- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/packages/stateless/hooks/useTranslatedTimeDeltaFormatter.ts b/packages/stateless/hooks/useTranslatedTimeDeltaFormatter.ts index be4c9c1a7..6130e0af0 100644 --- a/packages/stateless/hooks/useTranslatedTimeDeltaFormatter.ts +++ b/packages/stateless/hooks/useTranslatedTimeDeltaFormatter.ts @@ -1,5 +1,5 @@ import { useTranslation } from 'react-i18next' -import { Formatter } from 'react-timeago' +import { Formatter, Suffix, Unit } from 'react-timeago' export interface UseTranslatedTimeDeltaFormatterOptions { // Whether or not to show words around the time delta. If false, the time is @@ -10,18 +10,42 @@ export interface UseTranslatedTimeDeltaFormatterOptions { futureMode?: 'left' | 'in' } +const MINUTE = 60 +const HOUR = MINUTE * 60 +const DAY = HOUR * 24 +const WEEK = DAY * 7 +const MONTH = DAY * 30 +const YEAR = DAY * 365 + export const useTranslatedTimeDeltaFormatter = ({ words, futureMode = 'left', }: UseTranslatedTimeDeltaFormatterOptions): Formatter => { const { t } = useTranslation() - const timeDeltaFormatter: Formatter = (value, unit, suffix) => { - const lessThanOneMinute = unit === 'second' && value < 60 - if (lessThanOneMinute) { - value = 1 - unit = 'minute' - } + const timeDeltaFormatter = ( + _value: number, + _unit: Unit, + suffix: Suffix, + epochMiliseconds: number, + _nextFormatter: Formatter, + now: () => number + ) => { + const seconds = Math.round(Math.abs(now() - epochMiliseconds) / 1000) + const lessThanOneMinute = seconds < MINUTE + + // Manually improve granularity over default timeago formatter. + const [value, unit] = lessThanOneMinute + ? [1, 'minute'] + : seconds < HOUR + ? [Math.round(seconds / MINUTE), 'minute'] + : seconds < DAY + ? [Math.round(seconds / HOUR), 'hour'] + : seconds < MONTH + ? [Math.round(seconds / DAY), 'day'] + : seconds < YEAR + ? [Math.round(seconds / WEEK), 'week'] + : [Math.round(seconds / MONTH), 'month'] return t( words @@ -38,5 +62,5 @@ export const useTranslatedTimeDeltaFormatter = ({ ) } - return timeDeltaFormatter + return timeDeltaFormatter as Formatter }