This repository has been archived by the owner on Oct 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
72 lines (60 loc) · 1.81 KB
/
index.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
export interface UTCTimeOffset {
hour?: number;
minute?: number;
second?: number;
millisecond?: number;
}
export interface UTCTimeOpts {
startDatetime?: string | number | Date;
offset?: UTCTimeOffset;
}
function isValidDatetime(datetime: any) {
return 'Invalid Date' !== `${new Date(datetime)}`;
}
function isNotANumber(value: any) {
return value != null && isNaN(+value);
}
export function utcTimeSync({
startDatetime,
offset,
}: UTCTimeOpts = {} as UTCTimeOpts) {
const isNullishDatetime = null == startDatetime;
if (!isNullishDatetime && !isValidDatetime(startDatetime)) {
throw new TypeError(
`Expected 'startDatetime' to be a valid datetime, but received '${startDatetime}'`);
}
const {
hour = 0,
minute = 0,
second = 0,
millisecond = 0,
}: UTCTimeOffset = offset || {};
if (isNotANumber(hour)) {
throw new TypeError(`Expected 'offset.hour' to be a number, but received '${hour}'`);
}
if (isNotANumber(minute)) {
throw new TypeError(`Expected 'offset.minute' to be a number, but received '${minute}'`);
}
if (isNotANumber(second)) {
throw new TypeError(`Expected 'offset.second' to be a number, but received '${second}'`);
}
if (isNotANumber(millisecond)) {
throw new TypeError(
`Expected 'offset.millisecond' to be a number, but received '${millisecond}'`);
}
const newDatetime = isNullishDatetime
? new Date()
: new Date(startDatetime as string);
return new Date(Date.UTC(
newDatetime.getUTCFullYear(),
newDatetime.getUTCMonth(),
newDatetime.getUTCDate(),
newDatetime.getUTCHours() + hour,
newDatetime.getUTCMinutes() + minute,
newDatetime.getUTCSeconds() + second,
newDatetime.getUTCMilliseconds() + millisecond
));
}
export async function utcTime(opts?: UTCTimeOpts) {
return utcTimeSync(opts);
}