This repository has no description
1const DIVISIONS: { amount: number; unit: Intl.RelativeTimeFormatUnit }[] = [
2 { amount: 60, unit: "seconds" },
3 { amount: 60, unit: "minutes" },
4 { amount: 24, unit: "hours" },
5 { amount: 7, unit: "days" },
6 { amount: 4.34524, unit: "weeks" },
7 { amount: 12, unit: "months" },
8 { amount: Number.POSITIVE_INFINITY, unit: "years" }
9];
10
11const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
12const dtf = new Intl.DateTimeFormat("en", { year: "numeric", month: "short", day: "numeric" });
13
14// "3 days ago", "in 2 hours", etc.
15export const relativeTime = (input: string | Date, now: Date = new Date()): string => {
16 const date = typeof input === "string" ? new Date(input) : input;
17 if (Number.isNaN(date.getTime())) return "";
18 let duration = (date.getTime() - now.getTime()) / 1000;
19 for (const division of DIVISIONS) {
20 if (Math.abs(duration) < division.amount)
21 return rtf.format(Math.round(duration), division.unit);
22 duration /= division.amount;
23 }
24 return rtf.format(Math.round(duration), "years");
25};
26export const compactRelativeTime = (input: string | Date, now: Date = new Date()): string => {
27 const date = typeof input === "string" ? new Date(input) : input;
28 if (Number.isNaN(date.getTime())) return "";
29 let duration = Math.abs((now.getTime() - date.getTime()) / 1000);
30 const suffix = date.getTime() > now.getTime() ? "from now" : "ago";
31
32 if (duration < 60) return `${Math.floor(duration)}s ${suffix}`;
33 duration /= 60;
34 if (duration < 60) return `${Math.floor(duration)}m ${suffix}`;
35 duration /= 60;
36 if (duration < 24) return `${Math.floor(duration)}h ${suffix}`;
37 duration /= 24;
38 if (duration < 7) return `${Math.floor(duration)}d ${suffix}`;
39 duration /= 7;
40 if (duration < 4.34524) return `${Math.floor(duration)}w ${suffix}`;
41 duration /= 4.34524;
42 if (duration < 12) return `${Math.floor(duration)}mo ${suffix}`;
43 duration /= 12;
44 return `${Math.floor(duration)}y ${suffix}`;
45};
46
47export const formatDate = (input: string | Date): string => {
48 const date = typeof input === "string" ? new Date(input) : input;
49 return Number.isNaN(date.getTime()) ? "" : dtf.format(date);
50};