-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrfcdate.ts
54 lines (46 loc) · 1.31 KB
/
rfcdate.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
/*
* Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
*/
const dateRE = /^\d{4}-\d{2}-\d{2}$/;
export class RFCDate {
private serialized: string;
/**
* Creates a new RFCDate instance using today's date.
*/
static today(): RFCDate {
return new RFCDate(new Date());
}
/**
* Creates a new RFCDate instance using the provided input.
* If a string is used then in must be in the format YYYY-MM-DD.
*
* @param date A Date object or a date string in YYYY-MM-DD format
* @example
* new RFCDate("2022-01-01")
* @example
* new RFCDate(new Date())
*/
constructor(date: Date | string) {
if (typeof date === "string" && !dateRE.test(date)) {
throw new RangeError(
"RFCDate: date strings must be in the format YYYY-MM-DD: " + date,
);
}
const value = new Date(date);
if (isNaN(+value)) {
throw new RangeError("RFCDate: invalid date provided: " + date);
}
this.serialized = value.toISOString().slice(0, "YYYY-MM-DD".length);
if (!dateRE.test(this.serialized)) {
throw new TypeError(
`RFCDate: failed to build valid date with given value: ${date} serialized to ${this.serialized}`,
);
}
}
toJSON(): string {
return this.toString();
}
toString(): string {
return this.serialized;
}
}