Skip to content

Commit

Permalink
improve time ago granularity
Browse files Browse the repository at this point in the history
  • Loading branch information
NoahSaso committed Nov 20, 2024
1 parent d191075 commit 20f3b5c
Showing 1 changed file with 32 additions and 8 deletions.
40 changes: 32 additions & 8 deletions packages/stateless/hooks/useTranslatedTimeDeltaFormatter.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -38,5 +62,5 @@ export const useTranslatedTimeDeltaFormatter = ({
)
}

return timeDeltaFormatter
return timeDeltaFormatter as Formatter
}

0 comments on commit 20f3b5c

Please sign in to comment.