|
| 1 | +/* |
| 2 | + * Filename: timezoneless-date.ts |
| 3 | + * Author: simshadows <contact@simshadows.com> |
| 4 | + * License: GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later) |
| 5 | + * |
| 6 | + * A wrapper class to enforce the use of a pre-existing date implementation |
| 7 | + * as a simple timezoneless calendar date. |
| 8 | + */ |
| 9 | + |
| 10 | +import dayjs from "dayjs"; |
| 11 | +//import utc from "dayjs/plugin/utc"; |
| 12 | + |
| 13 | +//dayjs.extend(utc); |
| 14 | + |
| 15 | +const iso8601DateRegex = /^[0-9]{4}-[01][0-9]-[0-3][0-9]$/; |
| 16 | + |
| 17 | +export class TimezonelessDate { |
| 18 | + private __d: dayjs.Dayjs; |
| 19 | + |
| 20 | + /* |
| 21 | + * y is the calendar year |
| 22 | + * m is an integer 0-11 |
| 23 | + * d is an integer 1-31 |
| 24 | + */ |
| 25 | + constructor(y: number, m: number, d: number) { |
| 26 | + this.__d = dayjs(0).year(y).month(m).date(d); |
| 27 | + } |
| 28 | + |
| 29 | + toString(): string { |
| 30 | + return this.toISOString(); |
| 31 | + } |
| 32 | + toISOString(): string { |
| 33 | + return this.__d.format("YYYY-MM-DD"); |
| 34 | + } |
| 35 | + toDebugString(): string { |
| 36 | + return this.__d.toISOString(); |
| 37 | + } |
| 38 | + |
| 39 | + isAfter(other: TimezonelessDate): boolean { |
| 40 | + return this.__d.isAfter(other.__d, "date"); |
| 41 | + } |
| 42 | + |
| 43 | + static parseISODate(s: string): TimezonelessDate { |
| 44 | + if (s.length !== 10) { |
| 45 | + throw new Error(`Failed to parse string as a date. Must be exactly 10 characters. Instead got: ${s}`); |
| 46 | + } |
| 47 | + if (!iso8601DateRegex.test(s)) { |
| 48 | + throw new Error(`Failed to parse string as a date. String must be an ISO8601 date. Instead got: ${s}`); |
| 49 | + } |
| 50 | + const subStrs = s.split("-"); |
| 51 | + const y = subStrs[0]; |
| 52 | + const m = subStrs[1]; |
| 53 | + const d = subStrs[2]; |
| 54 | + if ((subStrs.length !== 3) || (!y) || (!m) || (!d)) { |
| 55 | + throw new Error("Expected three integers."); |
| 56 | + } |
| 57 | + return new TimezonelessDate(Number(y), Number(m) - 1, Number(d)); |
| 58 | + } |
| 59 | +} |
| 60 | + |
0 commit comments