kaneo (minimalist kanban) fork to experiment adding a tangled integration
github.com/usekaneo/kaneo
1import { i18n } from "./i18n";
2
3type DateInput = Date | string | number;
4
5function toDate(input: DateInput) {
6 return input instanceof Date ? input : new Date(input);
7}
8
9function getLocale(locale?: string) {
10 return locale || i18n.resolvedLanguage || i18n.language || "en-US";
11}
12
13export function formatDate(
14 value: DateInput,
15 options?: Intl.DateTimeFormatOptions,
16 locale?: string,
17) {
18 return new Intl.DateTimeFormat(getLocale(locale), options).format(
19 toDate(value),
20 );
21}
22
23export function formatDateShort(value: DateInput, locale?: string) {
24 return formatDate(
25 value,
26 {
27 month: "short",
28 day: "numeric",
29 },
30 locale,
31 );
32}
33
34export function formatDateMedium(value: DateInput, locale?: string) {
35 return formatDate(
36 value,
37 {
38 month: "short",
39 day: "numeric",
40 year: "numeric",
41 },
42 locale,
43 );
44}
45
46/** Locale-aware full date and time (for tooltips next to relative labels like "yesterday"). */
47export function formatDateTime(value: DateInput, locale?: string) {
48 return formatDate(
49 value,
50 {
51 dateStyle: "medium",
52 timeStyle: "short",
53 },
54 locale,
55 );
56}
57
58export function formatRelativeTime(
59 value: DateInput,
60 locale?: string,
61 now = new Date(),
62) {
63 const target = toDate(value);
64 const diffMs = target.getTime() - now.getTime();
65 const diffSeconds = Math.round(diffMs / 1000);
66 const absSeconds = Math.abs(diffSeconds);
67
68 const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [
69 ["year", 60 * 60 * 24 * 365],
70 ["month", 60 * 60 * 24 * 30],
71 ["week", 60 * 60 * 24 * 7],
72 ["day", 60 * 60 * 24],
73 ["hour", 60 * 60],
74 ["minute", 60],
75 ["second", 1],
76 ];
77
78 const formatter = new Intl.RelativeTimeFormat(getLocale(locale), {
79 numeric: "auto",
80 });
81
82 for (const [unit, unitSeconds] of units) {
83 if (absSeconds >= unitSeconds || unit === "second") {
84 return formatter.format(Math.round(diffSeconds / unitSeconds), unit);
85 }
86 }
87
88 return formatter.format(0, "second");
89}