40 lines
1.1 KiB
TypeScript

export class DateOnly {
private readonly _ticks: number;
constructor(year: number, month: number, day: number);
constructor(date: Date);
constructor(date: string);
constructor(yearOrDate: number | Date | string, month?: number, day?: number) {
if (yearOrDate instanceof Date) {
this._ticks = yearOrDate.getTime();
} else if (typeof yearOrDate === 'number' && month !== undefined && day !== undefined) {
this._ticks = new Date(yearOrDate, month - 1, day).getTime();
} else if (typeof yearOrDate === 'string') {
const [year, month, day] = yearOrDate.split('-').map(Number);
this._ticks = new Date(year, month - 1, day).getTime();
} else {
throw new Error('Invalid constructor arguments');
}
}
get year(): number {
return new Date(this._ticks).getFullYear();
}
get month(): number {
return new Date(this._ticks).getMonth() + 1;
}
get day(): number {
return new Date(this._ticks).getDate();
}
get date(): Date {
return new Date(this._ticks);
}
toString(): string {
return `${this.year}-${String(this.month).padStart(2, '0')}-${String(this.day).padStart(2, '0')}`;
}
}