-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
date.ts
63 lines (51 loc) 路 1.42 KB
/
date.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
import { format } from "../deps/date.ts";
import { merge } from "../core/utils.ts";
import type { Helper, Site } from "../core.ts";
const formats = new Map([
["ATOM", "yyyy-MM-dd'T'HH:mm:ssXXX"],
["DATE", "yyyy-MM-dd"],
["DATETIME", "yyyy-MM-dd HH:mm:ss"],
["TIME", "HH:mm:ss"],
["HUMAN_DATE", "PPP"],
["HUMAN_DATETIME", "PPPppp"],
]);
export interface Options {
/** The name of the helper */
name: string;
/** The loaded locales */
locales: Record<string, unknown>;
/** Custom date formats */
formats: Record<string, string>;
}
// Default options
export const defaults: Options = {
name: "date",
locales: {},
formats: {},
};
/** A plugin to format Date values */
export default function (userOptions?: Partial<Options>) {
const options = merge(defaults, userOptions);
const defaultLocale = Object.keys(options.locales).shift();
return (site: Site) => {
site.filter(options.name, filter as Helper);
function filter(
date: string | Date,
pattern = "DATE",
lang = defaultLocale,
) {
if (!date) {
return;
}
if (date === "now") {
date = new Date();
} else if (!(date instanceof Date)) {
date = new Date(date);
}
const patt = options.formats[pattern] || formats.get(pattern) ||
pattern;
const locale = lang ? options.locales[lang] : undefined;
return format(date, patt, { locale });
}
};
}