-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTimeDistance.tsx
41 lines (35 loc) · 972 Bytes
/
TimeDistance.tsx
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
import { FC, HTMLAttributes } from 'react';
import { diffTime, TimeData } from 'web-utility';
export interface TimeDistanceProps extends HTMLAttributes<HTMLTimeElement> {
date: TimeData;
unitWords?: Record<string, string>;
beforeWord?: string;
afterWord?: string;
}
const UnitWords = {
ms: 'millisecond(s)',
s: 'second(s)',
m: 'minute(s)',
H: 'hour(s)',
D: 'day(s)',
W: 'week(s)',
M: 'month(s)',
Y: 'year(s)'
};
export const TimeDistance: FC<TimeDistanceProps> = ({
date,
unitWords = UnitWords,
beforeWord = ' before',
afterWord = ' after',
...props
}) => {
date = new Date(date);
const { distance, unit } = diffTime(date);
return (
<time {...props} dateTime={date.toJSON()} title={date.toLocaleString()}>
{Math.abs(distance)} {unitWords[unit]}
{distance < 0 ? beforeWord : afterWord}
</time>
);
};
TimeDistance.displayName = 'TimeDistance';