// dayjsImmutableDate.ts
import dayjs, { ConfigType, Dayjs } from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import {
BaseImmutableDate,
DateRangeMode,
UnitType,
} from './baseImmutableDate';
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(isBetween);
dayjs.tz.setDefault('Asia/Seoul');
export class DayjsImmutableDate implements BaseImmutableDate {
private readonly date: Dayjs;
constructor(date?: ConfigType) {
this.date = this.createDate(date);
}
public toISOString(): string {
return this.date.toISOString();
}
public isSame(date?: ConfigType, unitType?: UnitType): boolean {
return this.date.isSame(date, unitType);
}
public isBefore(date?: ConfigType): boolean {
return this.date.isBefore(date);
}
public isAfter(date?: ConfigType): boolean {
return this.date.isAfter(date);
}
public isBetween(
startDate: ConfigType,
endDate: ConfigType,
unitType?: UnitType,
dateRangeMode?: DateRangeMode,
) {
return this.date.isBetween(startDate, endDate, unitType, dateRangeMode);
}
private createDate(date?: ConfigType): Dayjs {
if (!this.isValidDate(date)) {
throw new Error('유효하지 않은 날짜 입력입니다.');
}
return this.parseDate(date);
}
private isValidDate(date?: ConfigType): boolean {
return dayjs(date).isValid();
}
private parseDate(date?: ConfigType): Dayjs {
if (
typeof date === 'string' &&
(date.endsWith('Z') || this.hasTimeZone(date))
) {
return dayjs.utc(date);
}
return dayjs.tz(date);
}
private hasTimeZone(date: string) {
const timeZonePattern = /[+-]\d{2}:\d{2}$/;
return timeZonePattern.test(date);
}
}
Leave a comment