-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathuseTranslatedTimeDeltaFormatter.ts
66 lines (59 loc) · 1.95 KB
/
useTranslatedTimeDeltaFormatter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { useTranslation } from 'react-i18next'
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
// just rendered as the value (e.g. 1 day). If true, the time would be
// rendered as "1 day ago", "1 day left", or "in 1 day".
words: boolean
// If date is in the future, use either "left" suffix or "in" prefix.
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 = (
_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
? suffix === 'ago'
? 'format.timeAgo'
: futureMode === 'left'
? 'format.timeLeft'
: 'format.inTime'
: 'format.time',
{
value: lessThanOneMinute ? '< 1' : value,
unit: t(`unit.${unit}s`, { count: value }).toLocaleLowerCase(),
}
)
}
return timeDeltaFormatter as Formatter
}