diff --git a/src/shared/structs/TimeOnly.ts b/src/shared/structs/TimeOnly.ts new file mode 100644 index 0000000..e97d823 --- /dev/null +++ b/src/shared/structs/TimeOnly.ts @@ -0,0 +1,44 @@ +export class TimeOnly { + + private readonly _ticks: number; + + constructor(hour: number, minute: number, second: number); + constructor(time: Date); + constructor(time: string); + constructor(hourOrTime: number | Date | string, minute?: number, second?: number) { + if (hourOrTime instanceof Date) { + this._ticks = hourOrTime.getTime(); + } else if (typeof hourOrTime === 'number' && minute !== undefined && second !== undefined) { + this._ticks = new Date(2000, 0, 1, hourOrTime, minute, second, 0).getTime() + } else if (typeof hourOrTime === 'string') { + const [h, m, s] = hourOrTime.split(':').map(Number); + this._ticks = new Date(2000, 0, 1, h, m, s, 0).getTime() + } else { + throw new Error('Invalid constructor arguments'); + } + } + + get minute(): number { + return new Date(this._ticks).getMinutes(); + } + + get hour(): number { + return new Date(this._ticks).getHours(); + } + + get second(): number { + return new Date(this._ticks).getSeconds(); + } + + get localTime(): string { + return new Date(this._ticks).toLocaleDateString(); + } + + toTimeWithoutSeconds(): string { + return `${String(this.hour).padStart(2, '0')}:${String(this.minute).padStart(2, '0')}` + } + + toString(): string { + return `${String(this.hour).padStart(2, '0')}:${String(this.minute).padStart(2, '0')}-${String(this.second).padStart(2, '0')}`; + } +}