forked from PeronGH/simple-ics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate.ts
69 lines (61 loc) · 1.75 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
64
65
66
67
68
69
export function parseDate(date: DateData | undefined) {
if (date === undefined) return;
if (date instanceof Date) {
date = [
date.getFullYear(),
date.getMonth() + 1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
}
return formatDate(date);
}
type DateArray = number[];
export type DateData = DateArray | Date;
// The following code is copied from https://github.com/adamgibbons/ics/blob/master/src/utils/format-date.js
// Tiny modification is done to make it compatible with typescript
const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);
function formatDate(
args: number[] = [],
outputType = 'local',
inputType = 'local'
) {
if (Array.isArray(args) && args.length === 3) {
const [year, month, date] = args;
return `${year}${pad(month)}${pad(date)}`;
}
let outDate = new Date(new Date().setUTCSeconds(0, 0));
if (Array.isArray(args) && args.length > 0 && args[0]) {
const [year, month, date, hours = 0, minutes = 0, seconds = 0] = args;
if (inputType === 'local') {
outDate = new Date(year, month - 1, date, hours, minutes, seconds);
} else {
outDate = new Date(
Date.UTC(year, month - 1, date, hours, minutes, seconds)
);
}
}
if (outputType === 'local') {
return [
outDate.getFullYear(),
pad(outDate.getMonth() + 1),
pad(outDate.getDate()),
'T',
pad(outDate.getHours()),
pad(outDate.getMinutes()),
pad(outDate.getSeconds()),
].join('');
}
return [
outDate.getUTCFullYear(),
pad(outDate.getUTCMonth() + 1),
pad(outDate.getUTCDate()),
'T',
pad(outDate.getUTCHours()),
pad(outDate.getUTCMinutes()),
pad(outDate.getUTCSeconds()),
'Z',
].join('');
}