This repository was archived by the owner on Oct 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathtime-difference.js
79 lines (73 loc) · 2.14 KB
/
time-difference.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
// @flow
const MS_PER_SECOND = 1000;
const MS_PER_MINUTE = 60000;
const MS_PER_HOUR = 3600000;
const MS_PER_DAY = 86400000;
const MS_PER_YEAR = 31536000000;
export function timeDifferenceShort(current: number, previous: number) {
const elapsed = current - previous;
if (elapsed < MS_PER_MINUTE) {
return Math.round(elapsed / MS_PER_SECOND) + 's';
} else if (elapsed < MS_PER_HOUR) {
return Math.round(elapsed / MS_PER_MINUTE) + 'm';
} else if (elapsed < MS_PER_DAY) {
return Math.round(elapsed / MS_PER_HOUR) + 'h';
} else if (elapsed < MS_PER_YEAR) {
return Math.round(elapsed / MS_PER_DAY) + 'd';
} else {
return Math.round(elapsed / MS_PER_YEAR) + 'y';
}
}
export function timeDifference(current: number, previous: ?number): string {
if (!previous) return '';
const msPerMinute = 60 * 1000;
const msPerHour = msPerMinute * 60;
const msPerDay = msPerHour * 24;
const msPerMonth = msPerDay * 30;
const msPerYear = msPerDay * 365;
let elapsed = current - previous;
if (elapsed < msPerMinute) {
return 'Just now';
} else if (elapsed < msPerHour) {
const now = Math.round(elapsed / msPerMinute);
if (now === 1) {
return '1 minute ago';
} else {
return `${now} minutes ago`;
}
} else if (elapsed < msPerDay) {
const now = Math.round(elapsed / msPerHour);
if (now === 1) {
return '1 hour ago';
} else {
return `${now} hours ago`;
}
} else if (elapsed < msPerMonth) {
const now = Math.round(elapsed / msPerDay);
if (now === 1) {
return 'Yesterday';
} else if (now >= 7 && now <= 13) {
return '1 week ago';
} else if (now >= 14 && now <= 20) {
return '2 weeks ago';
} else if (now >= 21 && now <= 28) {
return '3 weeks ago';
} else {
return `${now} days ago`;
}
} else if (elapsed < msPerYear) {
const now = Math.round(elapsed / msPerMonth);
if (now === 1) {
return '1 month ago';
} else {
return `${now} months ago`;
}
} else {
const now = Math.round(elapsed / msPerYear);
if (now === 1) {
return '1 year ago';
} else {
return `${now} years ago`;
}
}
}