-
-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathuse-formatters.ts
83 lines (66 loc) · 2.04 KB
/
use-formatters.ts
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
80
81
82
83
import { format, formatDistance } from "date-fns";
/* eslint import/namespace: ['error', { allowComputed: true }] */
import * as Locales from "date-fns/locale";
const cache = {
currency: "",
};
export function resetCurrency() {
cache.currency = "";
}
export async function useFormatCurrency() {
if (cache.currency === "") {
const client = useUserApi();
const { data: group } = await client.group.get();
if (group) {
cache.currency = group.currency;
}
}
return (value: number | string) => fmtCurrency(value, cache.currency, getLocaleCode());
}
export type DateTimeFormat = "relative" | "long" | "short" | "human";
export type DateTimeType = "date" | "time" | "datetime";
export function getLocaleCode() {
const { $i18nGlobal } = useNuxtApp();
return ($i18nGlobal?.locale?.value as string) ?? "en-US";
}
function getLocaleForDate() {
const localeCode = getLocaleCode();
const lang = localeCode.length > 1 ? localeCode.substring(0, 2) : localeCode;
const region = localeCode.length > 2 ? localeCode.substring(3) : "";
return Locales[(lang + region) as keyof typeof Locales] ?? Locales[lang as keyof typeof Locales] ?? Locales.enUS;
}
export function fmtDate(
value: string | Date | number,
fmt: DateTimeFormat = "human",
type: DateTimeType = "date"
): string {
const dt = typeof value === "string" || typeof value === "number" ? new Date(value) : value;
if (!dt || !validDate(dt)) {
return "";
}
const localeOptions = { locale: getLocaleForDate() };
if (fmt === "relative") {
return `${formatDistance(dt, new Date(), { ...localeOptions, addSuffix: true })} (${fmtDate(dt, "short", "date")})`;
}
if (type === "time") {
return format(dt, "p", localeOptions);
}
let formatStr = "";
switch (fmt) {
case "human":
formatStr = "PPP";
break;
case "long":
formatStr = "PP";
break;
case "short":
formatStr = "P";
break;
default:
return "";
}
if (type === "datetime") {
formatStr += "p";
}
return format(dt, formatStr, localeOptions);
}