UNPKG

917 BJavaScriptView Raw
1const times = [
2 [1000, 60000, "sec"],
3 [60000, 3600000, "min"],
4 [3600000, 86400000, "hour"],
5 [86400000, 604800000, "day"],
6 [604800000, 2628000000, "week"],
7 [2628000000, 31536000000, "month"],
8 [31536000000, Infinity, "year"],
9];
10
11export function timerel(date, {noAffix = false} = {}) {
12 const ref = Date.now();
13
14 date = typeof date === "number" ? date : Date.parse(date);
15 if (Number.isNaN(date)) return "unknown";
16
17 let future = false;
18 let diff = ref - date;
19
20 if (diff < 0) {
21 future = true;
22 diff = Math.abs(diff);
23 }
24 if (diff < 10000) return "now";
25
26 let num, suffix;
27 for (let i = 0, len = times.length; i < len; i++) {
28 const time = times[i];
29 if (diff >= time[1]) continue;
30 num = Math.floor(diff / time[0]);
31 suffix = time[2] + (num > 1 ? "s" : "");
32 break;
33 }
34
35 return `${future && !noAffix ? "in " : ""}${num} ${suffix}${!future && !noAffix ? " ago" : ""}`;
36}