feat: enhance DateService with timezone support and improved date manipulation methods
This commit is contained in:
@@ -1,64 +1,196 @@
|
||||
/**
|
||||
* ------------------------------------------------------------
|
||||
* DateService
|
||||
* ------------------------------------------------------------
|
||||
* Centralized date and time utility built on top of Day.js.
|
||||
*
|
||||
* Features:
|
||||
* - Global timezone normalization
|
||||
* - Safe cloning with timezone consistency
|
||||
* - Fluent and immutable API
|
||||
* - ISO 8601 compliant output
|
||||
* - Explicit Indonesian timezone abbreviation support
|
||||
*
|
||||
* ⚠️ Day.js plugins MUST be initialized before using DateService.
|
||||
* ------------------------------------------------------------
|
||||
*/
|
||||
|
||||
import dayjs, { Dayjs, OpUnitType, ManipulateType } from 'dayjs';
|
||||
import utc from 'dayjs/plugin/utc';
|
||||
import timezone from 'dayjs/plugin/timezone';
|
||||
import advancedFormat from 'dayjs/plugin/advancedFormat';
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
* Day.js Bootstrap
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
dayjs.extend(advancedFormat);
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
* Types
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* FIX: Tambahkan 'Dayjs' ke dalam union type ini.
|
||||
* Ini memberitahu TS bahwa input boleh berupa string, date, atau object Dayjs itu sendiri.
|
||||
* Accepted input formats for DateService.
|
||||
*/
|
||||
export type DateInput = string | number | Date | Dayjs | null | undefined;
|
||||
|
||||
export type TimeUnit = 'day' | 'week' | 'month' | 'year' | 'hour' | 'minute' | 'second';
|
||||
/**
|
||||
* Supported time units for manipulation and comparison.
|
||||
*/
|
||||
export type TimeUnit = 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second';
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
* Constants
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* Explicit mapping for Indonesian timezone abbreviations.
|
||||
* This avoids ambiguity and ensures consistent output.
|
||||
*/
|
||||
const INDONESIA_TZ_MAP: Record<string, string> = {
|
||||
'Asia/Jakarta': 'WIB',
|
||||
'Asia/Pontianak': 'WIB',
|
||||
'Asia/Bangkok': 'WIB',
|
||||
'Asia/Makassar': 'WITA',
|
||||
'Asia/Ujung_Pandang': 'WITA',
|
||||
'Asia/Jayapura': 'WIT',
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
* Interfaces
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* Fluent date manipulation interface.
|
||||
* All methods are immutable and return a new instance.
|
||||
*/
|
||||
interface IDateManager {
|
||||
format(formatString?: string): string;
|
||||
format(format?: string): string;
|
||||
add(value: number, unit: TimeUnit): IDateManager;
|
||||
subtract(value: number, unit: TimeUnit): IDateManager;
|
||||
|
||||
// Update: Parameter sekarang support DateService instance juga (untuk DX lebih baik)
|
||||
isBefore(date: DateInput | DateService): boolean;
|
||||
isAfter(date: DateInput | DateService): boolean;
|
||||
isSame(date: DateInput | DateService, unit?: TimeUnit): boolean;
|
||||
diff(date: DateInput | DateService, unit: TimeUnit, precise?: boolean): number;
|
||||
|
||||
toISOString(): string;
|
||||
toDate(): Date;
|
||||
diffCalendarDay(date: DateInput | DateService): number;
|
||||
startOf(unit: TimeUnit): IDateManager;
|
||||
endOf(unit: TimeUnit): IDateManager;
|
||||
toISOString(): string;
|
||||
toDate(): Date;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
* DateService
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* Application-wide date abstraction.
|
||||
*
|
||||
* All instances are automatically normalized
|
||||
* to a single global timezone.
|
||||
*/
|
||||
export class DateService implements IDateManager {
|
||||
// Kita expose _date sebagai public readonly atau getter jika perlu akses raw dayjs
|
||||
// Tapi untuk strict encapsulation, keep private.
|
||||
private readonly _date: Dayjs;
|
||||
|
||||
constructor(date?: DateInput | DateService) {
|
||||
// FIX: Handle jika inputnya adalah instance dari DateService lain
|
||||
if (date instanceof DateService) {
|
||||
this._date = date.getRaw();
|
||||
} else {
|
||||
this._date = dayjs(date);
|
||||
}
|
||||
/**
|
||||
* Global default timezone.
|
||||
* Used by all DateService instances.
|
||||
*/
|
||||
private static _defaultTimezone: string = dayjs.tz.guess();
|
||||
|
||||
if (!this._date.isValid()) {
|
||||
console.warn(`[DateService] Invalid date: ${date}. Fallback to now.`);
|
||||
this._date = dayjs();
|
||||
/* ----------------------------------------------------------------
|
||||
* Global Configuration
|
||||
* ---------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Set the global timezone for the application.
|
||||
*
|
||||
* @example
|
||||
* DateService.setGlobalConfig('Asia/Jakarta');
|
||||
*/
|
||||
static setGlobalConfig(timezone: string): void {
|
||||
try {
|
||||
dayjs().tz(timezone);
|
||||
DateService._defaultTimezone = timezone;
|
||||
} catch {
|
||||
console.error(`[DateService] Invalid timezone "${timezone}". Using previous value.`);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper internal untuk mengambil raw object (diperlukan untuk interaksi antar instance)
|
||||
public getRaw(): Dayjs {
|
||||
return this._date;
|
||||
/**
|
||||
* Get the currently active global timezone.
|
||||
*/
|
||||
static getGlobalTimezone(): string {
|
||||
return DateService._defaultTimezone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a DateService instance representing the current moment.
|
||||
*/
|
||||
static now(): DateService {
|
||||
return new DateService();
|
||||
}
|
||||
|
||||
// --- Implementation Methods ---
|
||||
/* ----------------------------------------------------------------
|
||||
* Constructor
|
||||
* ---------------------------------------------------------------- */
|
||||
|
||||
format(formatString: string = 'YYYY-MM-DD'): string {
|
||||
return this._date.format(formatString);
|
||||
constructor(date?: DateInput | DateService) {
|
||||
if (date instanceof DateService) {
|
||||
this._date = date.getRaw().tz(DateService._defaultTimezone);
|
||||
} else {
|
||||
this._date = dayjs(date).tz(DateService._defaultTimezone);
|
||||
}
|
||||
|
||||
if (!this._date.isValid()) {
|
||||
console.warn('[DateService] Invalid date input. Falling back to now().');
|
||||
this._date = dayjs().tz(DateService._defaultTimezone);
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------
|
||||
* Internal Utilities
|
||||
* ---------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Access the internal Day.js instance.
|
||||
* Intended for advanced usage only.
|
||||
*/
|
||||
getRaw(): Dayjs {
|
||||
return this._date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize input into Day.js using the global timezone.
|
||||
*/
|
||||
private toDayjs(date: DateInput | DateService): Dayjs {
|
||||
return date instanceof DateService ? date.getRaw() : dayjs(date).tz(DateService._defaultTimezone);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------
|
||||
* Formatting & Conversion
|
||||
* ---------------------------------------------------------------- */
|
||||
|
||||
format(format: string = 'YYYY-MM-DD'): string {
|
||||
return this._date.format(format);
|
||||
}
|
||||
|
||||
toISOString(): string {
|
||||
// Always returns UTC (ISO 8601 compliant)
|
||||
return this._date.toISOString();
|
||||
}
|
||||
|
||||
toDate(): Date {
|
||||
return this._date.toDate();
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------
|
||||
* Manipulation
|
||||
* ---------------------------------------------------------------- */
|
||||
|
||||
add(value: number, unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.add(value, unit as ManipulateType));
|
||||
}
|
||||
@@ -67,40 +199,6 @@ export class DateService implements IDateManager {
|
||||
return new DateService(this._date.subtract(value, unit as ManipulateType));
|
||||
}
|
||||
|
||||
// Helper private untuk normalisasi input (menangani DateService vs DateInput biasa)
|
||||
private _toDayjs(date: DateInput | DateService): Dayjs {
|
||||
if (date instanceof DateService) {
|
||||
return date.getRaw();
|
||||
}
|
||||
return dayjs(date);
|
||||
}
|
||||
|
||||
isBefore(date: DateInput | DateService): boolean {
|
||||
return this._date.isBefore(this._toDayjs(date));
|
||||
}
|
||||
|
||||
isAfter(date: DateInput | DateService): boolean {
|
||||
return this._date.isAfter(this._toDayjs(date));
|
||||
}
|
||||
|
||||
isSame(date: DateInput | DateService, unit?: TimeUnit): boolean {
|
||||
return this._date.isSame(this._toDayjs(date), unit as OpUnitType);
|
||||
}
|
||||
|
||||
diff(date: DateInput | DateService, unit: TimeUnit, precise: boolean = false): number {
|
||||
return this._date.diff(this._toDayjs(date), unit as OpUnitType, precise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Menghitung selisih HARI KALENDER.
|
||||
* Mengabaikan jam/menit, murni membandingkan tanggal.
|
||||
*/
|
||||
diffCalendarDay(date: DateInput | DateService): number {
|
||||
const target = this._toDayjs(date);
|
||||
// Reset keduanya ke jam 00:00:00 sebelum diff
|
||||
return this._date.startOf('day').diff(target.startOf('day'), 'day');
|
||||
}
|
||||
|
||||
startOf(unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.startOf(unit as OpUnitType));
|
||||
}
|
||||
@@ -109,32 +207,90 @@ export class DateService implements IDateManager {
|
||||
return new DateService(this._date.endOf(unit as OpUnitType));
|
||||
}
|
||||
|
||||
toISOString(): string {
|
||||
return this._date.toISOString();
|
||||
/* ----------------------------------------------------------------
|
||||
* Comparison
|
||||
* ---------------------------------------------------------------- */
|
||||
|
||||
isBefore(date: DateInput | DateService): boolean {
|
||||
return this._date.isBefore(this.toDayjs(date));
|
||||
}
|
||||
|
||||
toDate(): Date {
|
||||
return this._date.toDate();
|
||||
isAfter(date: DateInput | DateService): boolean {
|
||||
return this._date.isAfter(this.toDayjs(date));
|
||||
}
|
||||
|
||||
isSame(date: DateInput | DateService, unit?: TimeUnit): boolean {
|
||||
return this._date.isSame(this.toDayjs(date), unit as OpUnitType);
|
||||
}
|
||||
|
||||
diff(date: DateInput | DateService, unit: TimeUnit, precise: boolean = false): number {
|
||||
return this._date.diff(this.toDayjs(date), unit as OpUnitType, precise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calendar-day difference ignoring time components.
|
||||
*/
|
||||
diffCalendarDay(date: DateInput | DateService): number {
|
||||
const target = this.toDayjs(date);
|
||||
return this._date.startOf('day').diff(target.startOf('day'), 'day');
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------
|
||||
* Epoch Helpers
|
||||
* ---------------------------------------------------------------- */
|
||||
|
||||
get timestamp(): number {
|
||||
return this._date.valueOf();
|
||||
}
|
||||
|
||||
/* Mengembalikan Epoch dalam Milliseconds (13 digit).
|
||||
* Contoh: 1704067200000
|
||||
* Gunakan ini untuk kalkulasi di Frontend JS/TS.
|
||||
*/
|
||||
get epochMillis(): number {
|
||||
return this._date.valueOf();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengembalikan Epoch dalam Seconds (10 digit).
|
||||
* Contoh: 1704067200
|
||||
* Gunakan ini untuk kirim ke Backend (PHP, Golang, Python, dll) atau JWT.
|
||||
*/
|
||||
get epochSeconds(): number {
|
||||
return this._date.unix();
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------
|
||||
* Timezone Utilities
|
||||
* ---------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Retrieve supported IANA timezones from the runtime environment.
|
||||
*/
|
||||
static getSupportedTimezones(): string[] {
|
||||
if (typeof Intl !== 'undefined' && typeof Intl.supportedValuesOf === 'function') {
|
||||
try {
|
||||
return Intl.supportedValuesOf('timeZone');
|
||||
} catch {
|
||||
console.warn('[DateService] Failed to retrieve timezones via Intl.');
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'UTC',
|
||||
'Asia/Jakarta',
|
||||
'Asia/Makassar',
|
||||
'Asia/Jayapura',
|
||||
'Asia/Singapore',
|
||||
'Asia/Tokyo',
|
||||
'Australia/Sydney',
|
||||
'Europe/London',
|
||||
'Europe/Paris',
|
||||
'America/New_York',
|
||||
'America/Los_Angeles',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable timezone abbreviation.
|
||||
*
|
||||
* Priority:
|
||||
* 1. Indonesian mapping (WIB / WITA / WIT)
|
||||
* 2. Day.js dynamic abbreviation (DST-safe)
|
||||
*/
|
||||
get timezoneAbbr(): string {
|
||||
const tz = DateService._defaultTimezone;
|
||||
return INDONESIA_TZ_MAP[tz] ?? this._date.format('z');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user