-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathuseDateLocalize.ts
More file actions
38 lines (30 loc) · 974 Bytes
/
useDateLocalize.ts
File metadata and controls
38 lines (30 loc) · 974 Bytes
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
import { LocaleContext } from "@dashboard/components/Locale";
import { useContext } from "react";
export type LocalizeDate = (date: string, format?: string) => string;
/**
* Backwards compat with old moment.js format.
*/
const FORMAT_OPTIONS: Record<string, Intl.DateTimeFormatOptions> = {
ll: { dateStyle: "medium" },
lll: { dateStyle: "medium", timeStyle: "short" },
llll: {
weekday: "short",
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
},
};
function useDateLocalize(): LocalizeDate {
const { locale } = useContext(LocaleContext);
return (date: string, format?: "ll" | "lll" | "llll" | string) => {
const parsed = new Date(date);
if (isNaN(parsed.getTime())) {
return "Invalid date";
}
const options = FORMAT_OPTIONS[format || "ll"] ?? FORMAT_OPTIONS.ll;
return new Intl.DateTimeFormat(locale, options).format(parsed);
};
}
export default useDateLocalize;