feat: enhance DateService with timezone support and improved date manipulation methods
This commit is contained in:
@@ -35,7 +35,7 @@ export const Primary: Story = {
|
|||||||
name: 'Button',
|
name: 'Button',
|
||||||
args: {
|
args: {
|
||||||
children: 'Hello',
|
children: 'Hello',
|
||||||
type: 'button',
|
type: 'submit',
|
||||||
style: {
|
style: {
|
||||||
color: 'blue',
|
color: 'blue',
|
||||||
border: '1px solid gray',
|
border: '1px solid gray',
|
||||||
|
|||||||
@@ -1,47 +1,53 @@
|
|||||||
import { DateService } from '@repo/utils';
|
import { DateService } from '@repo/utils';
|
||||||
import React, { useState, useEffect, useMemo } from 'react';
|
import React, { useState, useEffect, useMemo } from 'react';
|
||||||
|
|
||||||
// Mock Data untuk simulasi list tugas/tagihan
|
|
||||||
// Kita gunakan relative time agar mock data selalu relevan saat dijalankan
|
|
||||||
const MOCK_TASKS = [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
title: 'Bayar Server (Lusa)',
|
|
||||||
dueDate: DateService.now().add(2, 'day').toISOString(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
title: 'Laporan Bulanan (Lewat 5 Hari)',
|
|
||||||
dueDate: DateService.now().subtract(5, 'day').toISOString(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 3,
|
|
||||||
title: 'Meeting Tahunan (Bulan Depan)',
|
|
||||||
dueDate: DateService.now().add(1, 'month').toISOString(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 4,
|
|
||||||
title: 'Deadline Besok Pagi',
|
|
||||||
dueDate: DateService.now().add(1, 'day').startOf('day').toISOString(),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export const DateServiceExample: React.FC = () => {
|
export const DateServiceExample: React.FC = () => {
|
||||||
// 1. STATE: Waktu sekarang (untuk jam digital)
|
// --- 0. TIMEZONE CONFIGURATION (ROOT CONTROL) ---
|
||||||
const [currentTime, setCurrentTime] = useState<DateService>(DateService.now());
|
const [currentZone, setCurrentZone] = useState<string>(DateService.getGlobalTimezone());
|
||||||
|
|
||||||
// 2. STATE: Manipulasi tanggal interaktif
|
// Ambil list timezone dari helper static yang kita buat sebelumnya
|
||||||
|
const timezoneList = useMemo(() => DateService.getSupportedTimezones(), []);
|
||||||
|
|
||||||
|
// --- 1. STATE & DATA ---
|
||||||
|
|
||||||
|
// MOCK DATA dipindahkan ke sini & pakai useMemo
|
||||||
|
// Agar saat timezone ganti, tasks ini di-regenerate dengan waktu "Now" versi timezone baru.
|
||||||
|
const tasks = useMemo(() => {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
title: 'Bayar Server (Lusa)',
|
||||||
|
dueDate: DateService.now().add(2, 'day').toISOString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
title: 'Laporan Bulanan (Lewat 5 Hari)',
|
||||||
|
dueDate: DateService.now().subtract(5, 'day').toISOString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 3,
|
||||||
|
title: 'Meeting Tahunan (Bulan Depan)',
|
||||||
|
dueDate: DateService.now().add(1, 'month').toISOString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 4,
|
||||||
|
title: 'Deadline Besok Pagi',
|
||||||
|
dueDate: DateService.now().add(1, 'day').startOf('day').toISOString(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}, [currentZone]); // Dependency: currentZone
|
||||||
|
|
||||||
|
const [currentTime, setCurrentTime] = useState<DateService>(DateService.now());
|
||||||
const [selectedDate, setSelectedDate] = useState<DateService>(DateService.now());
|
const [selectedDate, setSelectedDate] = useState<DateService>(DateService.now());
|
||||||
|
|
||||||
// 3. STATE: Khusus Demo Logic Calendar (Besok jam 00:00 vs Sekarang)
|
// State demo logic calendar
|
||||||
// Ini untuk menjawab kenapa diff kadang 0 padahal beda hari
|
const [calendarTarget, setCalendarTarget] = useState(() => DateService.now().add(1, 'day').startOf('day'));
|
||||||
const [calendarTarget] = useState(() => DateService.now().add(1, 'day').startOf('day'));
|
|
||||||
|
|
||||||
// 4. MEMO: Nilai Epoch Static (Hanya diambil saat component mount)
|
// Static date (Memo kosong) -> Akan tetap di Timezone saat pertama kali load (kecuali di-refresh)
|
||||||
// Gunakan ini jika ingin nilai 'kapan user membuka halaman'
|
// Ini bagus untuk demo bahwa object lama tidak berubah (immutable) kecuali dibuat ulang.
|
||||||
const staticDate = useMemo(() => new DateService(), []);
|
const staticDate = useMemo(() => new DateService(), []);
|
||||||
|
|
||||||
// Effect untuk update jam setiap detik
|
// Effect update jam tiap detik
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setInterval(() => {
|
const timer = setInterval(() => {
|
||||||
setCurrentTime(DateService.now());
|
setCurrentTime(DateService.now());
|
||||||
@@ -49,25 +55,79 @@ export const DateServiceExample: React.FC = () => {
|
|||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Handler untuk tombol tambah/kurang hari
|
// --- HANDLER GANTI TIMEZONE ---
|
||||||
|
const handleZoneChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
|
const newZone = e.target.value;
|
||||||
|
setCurrentZone(newZone);
|
||||||
|
|
||||||
|
// 1. Set Global Config (Inti Perubahan)
|
||||||
|
DateService.setGlobalConfig(newZone);
|
||||||
|
|
||||||
|
// 2. Force Refresh State agar UI langsung berubah
|
||||||
|
// Kita buat instance baru agar mengambil config timezone terbaru
|
||||||
|
setCurrentTime(DateService.now());
|
||||||
|
|
||||||
|
// Kita recreate selectedDate dengan nilai raw yang sama, tapi context timezone baru
|
||||||
|
setSelectedDate((prev) => new DateService(prev.getRaw()));
|
||||||
|
|
||||||
|
// Recreate target demo calendar
|
||||||
|
setCalendarTarget(DateService.now().add(1, 'day').startOf('day'));
|
||||||
|
};
|
||||||
|
|
||||||
const handleAddDay = (days: number) => {
|
const handleAddDay = (days: number) => {
|
||||||
setSelectedDate((prev) => prev.add(days, 'day'));
|
setSelectedDate((prev) => prev.add(days, 'day'));
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-8 max-w-5xl mx-auto bg-gray-50 min-h-screen font-sans text-gray-800">
|
<div className="p-8 max-w-5xl mx-auto bg-gray-50 min-h-screen font-sans text-gray-800">
|
||||||
<h1 className="text-3xl font-bold mb-8 text-blue-900">DateService Feature Showcase</h1>
|
{/* HEADER & TIMEZONE CONTROLLER */}
|
||||||
|
<div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4 border-b border-gray-200 pb-6">
|
||||||
|
<h1 className="text-3xl font-bold text-blue-900">DateService Feature Showcase</h1>
|
||||||
|
|
||||||
|
<div className="bg-white p-3 rounded-lg shadow-sm border border-blue-100 flex items-center gap-3">
|
||||||
|
<label htmlFor="tz-switcher" className="text-xs font-bold text-gray-500 uppercase tracking-wide">
|
||||||
|
App Timezone:
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="tz-switcher"
|
||||||
|
value={currentZone}
|
||||||
|
onChange={handleZoneChange}
|
||||||
|
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 block p-1.5 outline-none font-mono"
|
||||||
|
>
|
||||||
|
{timezoneList.map((tz) => (
|
||||||
|
<option key={tz} value={tz}>
|
||||||
|
{tz}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
{/* --- CARD 1: REALTIME CLOCK --- */}
|
{/* --- CARD 1: REALTIME CLOCK --- */}
|
||||||
<div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 flex flex-col justify-between">
|
<div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 flex flex-col justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-2">Realtime Clock</h2>
|
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-2">Realtime Clock</h2>
|
||||||
<div className="text-4xl font-mono font-bold text-gray-900">{currentTime.format('HH:mm:ss')}</div>
|
|
||||||
<div className="text-lg text-gray-500 mt-1">{currentTime.format('dddd, DD MMMM YYYY')}</div>
|
<div className="flex flex-col">
|
||||||
|
<div className="text-4xl font-mono font-bold text-gray-900">{currentTime.format('HH:mm:ss')}</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 mt-2">
|
||||||
|
{/* UPDATE DI SINI: Gunakan .timezoneAbbr */}
|
||||||
|
<div className="text-sm font-bold text-blue-700 bg-blue-100 px-2 py-1 rounded border border-blue-200">
|
||||||
|
{/* Ini akan output "WIB", "WITA", atau "EST" */}
|
||||||
|
{currentTime.timezoneAbbr}
|
||||||
|
|
||||||
|
{/* Ini offset angka (+07:00) */}
|
||||||
|
<span className="opacity-60 text-xs ml-1">({currentTime.format('Z')})</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-lg text-gray-500 mt-2">{currentTime.format('dddd, DD MMMM YYYY')}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-4 text-xs bg-gray-100 p-2 rounded text-gray-500 font-mono break-all">
|
<div className="mt-4 text-xs bg-gray-100 p-2 rounded text-gray-500 font-mono break-all">
|
||||||
ISO: {currentTime.toISOString()}
|
ISO (UTC): {currentTime.toISOString()}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -79,7 +139,7 @@ export const DateServiceExample: React.FC = () => {
|
|||||||
{/* STATIC SECTION */}
|
{/* STATIC SECTION */}
|
||||||
<div className="bg-blue-50 p-3 rounded-lg border border-blue-100">
|
<div className="bg-blue-50 p-3 rounded-lg border border-blue-100">
|
||||||
<div className="text-xs font-bold text-blue-800 mb-1">STATIC (Load Once)</div>
|
<div className="text-xs font-bold text-blue-800 mb-1">STATIC (Load Once)</div>
|
||||||
<div className="text-xs text-blue-600 mb-2">Captured via useMemo([]), tidak berubah.</div>
|
<div className="text-xs text-blue-600 mb-2">Captured on mount (keeps original timezone).</div>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||||
@@ -95,7 +155,7 @@ export const DateServiceExample: React.FC = () => {
|
|||||||
{/* LIVE SECTION */}
|
{/* LIVE SECTION */}
|
||||||
<div className="bg-green-50 p-3 rounded-lg border border-green-100">
|
<div className="bg-green-50 p-3 rounded-lg border border-green-100">
|
||||||
<div className="text-xs font-bold text-green-800 mb-1">LIVE (Reactive)</div>
|
<div className="text-xs font-bold text-green-800 mb-1">LIVE (Reactive)</div>
|
||||||
<div className="text-xs text-green-600 mb-2">Updated every second (new instance).</div>
|
<div className="text-xs text-green-600 mb-2">Updated every second (follows dropdown).</div>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||||
@@ -110,49 +170,44 @@ export const DateServiceExample: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* --- CARD 3: CALENDAR LOGIC DEMO (Standard vs Calendar Diff) --- */}
|
{/* --- CARD 3: CALENDAR LOGIC DEMO --- */}
|
||||||
<div className="bg-indigo-50 p-6 rounded-xl shadow-sm border border-indigo-200 md:col-span-2">
|
<div className="bg-indigo-50 p-6 rounded-xl shadow-sm border border-indigo-200 md:col-span-2">
|
||||||
<h2 className="text-lg font-bold text-indigo-900 mb-4 flex items-center gap-2">
|
<h2 className="text-lg font-bold text-indigo-900 mb-4 flex items-center gap-2">
|
||||||
🗓️ Calendar Logic Demo (The "Zero Day" Issue)
|
🗓️ Calendar Logic Demo (The "Zero Day" Issue)
|
||||||
</h2>
|
</h2>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||||
{/* Info Section */}
|
|
||||||
<div className="text-sm text-indigo-800 space-y-2">
|
<div className="text-sm text-indigo-800 space-y-2">
|
||||||
<p>
|
<p>
|
||||||
Compare <strong>Current Time</strong> vs <strong>Tomorrow 00:00</strong>.
|
Compare <strong>Current Time</strong> vs <strong>Tomorrow 00:00</strong>.
|
||||||
</p>
|
</p>
|
||||||
<div className="bg-white/50 p-2 rounded">
|
<div className="bg-white/50 p-2 rounded">
|
||||||
<div className="flex justify-between text-xs">
|
<div className="flex justify-between text-xs">
|
||||||
<span>Now:</span>
|
<span>Now ({currentZone}):</span>
|
||||||
<span className="font-mono font-bold">{currentTime.format('HH:mm')}</span>
|
<span className="font-mono font-bold">{currentTime.format('HH:mm')}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between text-xs mt-1">
|
<div className="flex justify-between text-xs mt-1">
|
||||||
<span>Target:</span>
|
<span>Target (Start of Day):</span>
|
||||||
<span className="font-mono font-bold">{calendarTarget.format('DD MMM HH:mm')}</span>
|
<span className="font-mono font-bold">{calendarTarget.format('DD MMM HH:mm')}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Wrong Way */}
|
|
||||||
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-red-400">
|
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-red-400">
|
||||||
<div className="text-xs text-gray-400 uppercase font-bold">Standard .diff('day')</div>
|
<div className="text-xs text-gray-400 uppercase font-bold">Standard .diff('day')</div>
|
||||||
<div className="text-2xl font-bold text-red-600 mt-1">
|
<div className="text-2xl font-bold text-red-600 mt-1">
|
||||||
{calendarTarget.diff(currentTime, 'day')}{' '}
|
{calendarTarget.diff(currentTime, 'day')}{' '}
|
||||||
<span className="text-sm font-normal text-gray-500">Days</span>
|
<span className="text-sm font-normal text-gray-500">Days</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-red-500 mt-1">
|
<p className="text-xs text-red-500 mt-1">Hasil 0 jika jarak < 24 jam.</p>
|
||||||
Hasil 0 jika jarak < 24 jam. Kurang cocok untuk deadline "H-1".
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right Way */}
|
|
||||||
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-green-500">
|
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-green-500">
|
||||||
<div className="text-xs text-gray-400 uppercase font-bold">New .diffCalendarDay()</div>
|
<div className="text-xs text-gray-400 uppercase font-bold">New .diffCalendarDay()</div>
|
||||||
<div className="text-2xl font-bold text-green-600 mt-1">
|
<div className="text-2xl font-bold text-green-600 mt-1">
|
||||||
{calendarTarget.diffCalendarDay(currentTime)}{' '}
|
{calendarTarget.diffCalendarDay(currentTime)}{' '}
|
||||||
<span className="text-sm font-normal text-gray-500">Days</span>
|
<span className="text-sm font-normal text-gray-500">Days</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-green-600 mt-1">Hasil 1. Menghitung selisih tanggal kalender (ignore jam).</p>
|
<p className="text-xs text-green-600 mt-1">Hasil 1. Benar secara kalender.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -174,6 +229,7 @@ export const DateServiceExample: React.FC = () => {
|
|||||||
<div className="flex-1 text-center">
|
<div className="flex-1 text-center">
|
||||||
<span className="block text-3xl font-bold text-blue-900">{selectedDate.format('DD MMMM YYYY')}</span>
|
<span className="block text-3xl font-bold text-blue-900">{selectedDate.format('DD MMMM YYYY')}</span>
|
||||||
<span className="text-sm text-blue-600 font-medium">Selected Date State</span>
|
<span className="text-sm text-blue-600 font-medium">Selected Date State</span>
|
||||||
|
<span className="text-xs text-gray-400 block mt-1">Offset: {selectedDate.format('Z')}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
@@ -201,9 +257,11 @@ export const DateServiceExample: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* --- CARD 5: TASK LIST (IMPLEMENTATION REAL) --- */}
|
{/* --- CARD 5: TASK LIST (DYNAMIC) --- */}
|
||||||
<div className="mt-8 bg-white p-6 rounded-xl shadow-sm border border-gray-200">
|
<div className="mt-8 bg-white p-6 rounded-xl shadow-sm border border-gray-200">
|
||||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">Task List Implementation</h2>
|
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">
|
||||||
|
Task List Implementation (Timezone Aware)
|
||||||
|
</h2>
|
||||||
|
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full text-left border-collapse">
|
<table className="w-full text-left border-collapse">
|
||||||
@@ -212,22 +270,16 @@ export const DateServiceExample: React.FC = () => {
|
|||||||
<th className="py-3 px-4 rounded-tl-lg">Task Name</th>
|
<th className="py-3 px-4 rounded-tl-lg">Task Name</th>
|
||||||
<th className="py-3 px-4">Due Date</th>
|
<th className="py-3 px-4">Due Date</th>
|
||||||
<th className="py-3 px-4">Status Badge</th>
|
<th className="py-3 px-4">Status Badge</th>
|
||||||
<th className="py-3 px-4 rounded-tr-lg">Human Readable Countdown</th>
|
<th className="py-3 px-4 rounded-tr-lg">Countdown</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{MOCK_TASKS.map((task) => {
|
{tasks.map((task) => {
|
||||||
const dueDate = new DateService(task.dueDate);
|
const dueDate = new DateService(task.dueDate);
|
||||||
const now = DateService.now(); // Mengambil waktu 'live' dari state currentTime akan menyebabkan re-render tiap detik, tapi disini kita instantiate baru agar logic per baris bersih.
|
const now = DateService.now();
|
||||||
|
|
||||||
// Logic 1: Apakah sudah lewat? (Check absolute timestamp)
|
|
||||||
const isOverdue = now.isAfter(dueDate);
|
const isOverdue = now.isAfter(dueDate);
|
||||||
|
|
||||||
// Logic 2: Gunakan CALENDAR DIFF untuk countdown yang enak dibaca user
|
|
||||||
// Jika pakai diff() biasa, tugas besok pagi bisa dianggap '0 days left'
|
|
||||||
const daysDiff = dueDate.diffCalendarDay(now);
|
const daysDiff = dueDate.diffCalendarDay(now);
|
||||||
|
|
||||||
// Logic 3: Warning jika kurang dari 3 hari lagi (dan belum overdue)
|
|
||||||
const isDueSoon = !isOverdue && daysDiff <= 3;
|
const isDueSoon = !isOverdue && daysDiff <= 3;
|
||||||
|
|
||||||
let statusBadge;
|
let statusBadge;
|
||||||
@@ -256,11 +308,14 @@ export const DateServiceExample: React.FC = () => {
|
|||||||
return (
|
return (
|
||||||
<tr key={task.id} className={rowClass}>
|
<tr key={task.id} className={rowClass}>
|
||||||
<td className="py-3 px-4 font-medium text-gray-700">{task.title}</td>
|
<td className="py-3 px-4 font-medium text-gray-700">{task.title}</td>
|
||||||
<td className="py-3 px-4 text-gray-500 font-mono text-sm">{dueDate.format('DD MMM YYYY HH:mm')}</td>
|
<td className="py-3 px-4 text-gray-500 font-mono text-sm">
|
||||||
|
{dueDate.format('DD MMM YYYY HH:mm')}
|
||||||
|
<span className="text-[10px] text-gray-400 ml-1">{dueDate.format('Z')}</span>
|
||||||
|
</td>
|
||||||
<td className="py-3 px-4">{statusBadge}</td>
|
<td className="py-3 px-4">{statusBadge}</td>
|
||||||
<td className="py-3 px-4 text-sm text-gray-600 font-medium">
|
<td className="py-3 px-4 text-sm text-gray-600 font-medium">
|
||||||
{isOverdue ? (
|
{isOverdue ? (
|
||||||
`${Math.abs(daysDiff)} days late` // Gunakan Math.abs karena diff negatif
|
`${Math.abs(daysDiff)} days late`
|
||||||
) : daysDiff === 0 ? (
|
) : daysDiff === 0 ? (
|
||||||
<span className="text-amber-600">Today!</span>
|
<span className="text-amber-600">Today!</span>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -1,47 +1,53 @@
|
|||||||
import { DateService } from '@repo/utils';
|
import { DateService } from '@repo/utils';
|
||||||
import React, { useState, useEffect, useMemo } from 'react';
|
import React, { useState, useEffect, useMemo } from 'react';
|
||||||
|
|
||||||
// Mock Data untuk simulasi list tugas/tagihan
|
|
||||||
// Kita gunakan relative time agar mock data selalu relevan saat dijalankan
|
|
||||||
const MOCK_TASKS = [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
title: 'Bayar Server (Lusa)',
|
|
||||||
dueDate: DateService.now().add(2, 'day').toISOString(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
title: 'Laporan Bulanan (Lewat 5 Hari)',
|
|
||||||
dueDate: DateService.now().subtract(5, 'day').toISOString(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 3,
|
|
||||||
title: 'Meeting Tahunan (Bulan Depan)',
|
|
||||||
dueDate: DateService.now().add(1, 'month').toISOString(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 4,
|
|
||||||
title: 'Deadline Besok Pagi',
|
|
||||||
dueDate: DateService.now().add(1, 'day').startOf('day').toISOString(),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export const DateServiceComponent: React.FC = () => {
|
export const DateServiceComponent: React.FC = () => {
|
||||||
// 1. STATE: Waktu sekarang (untuk jam digital)
|
// --- 0. TIMEZONE CONFIGURATION (ROOT CONTROL) ---
|
||||||
const [currentTime, setCurrentTime] = useState<DateService>(DateService.now());
|
const [currentZone, setCurrentZone] = useState<string>(DateService.getGlobalTimezone());
|
||||||
|
|
||||||
// 2. STATE: Manipulasi tanggal interaktif
|
// Ambil list timezone dari helper static yang kita buat sebelumnya
|
||||||
|
const timezoneList = useMemo(() => DateService.getSupportedTimezones(), []);
|
||||||
|
|
||||||
|
// --- 1. STATE & DATA ---
|
||||||
|
|
||||||
|
// MOCK DATA dipindahkan ke sini & pakai useMemo
|
||||||
|
// Agar saat timezone ganti, tasks ini di-regenerate dengan waktu "Now" versi timezone baru.
|
||||||
|
const tasks = useMemo(() => {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
title: 'Bayar Server (Lusa)',
|
||||||
|
dueDate: DateService.now().add(2, 'day').toISOString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
title: 'Laporan Bulanan (Lewat 5 Hari)',
|
||||||
|
dueDate: DateService.now().subtract(5, 'day').toISOString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 3,
|
||||||
|
title: 'Meeting Tahunan (Bulan Depan)',
|
||||||
|
dueDate: DateService.now().add(1, 'month').toISOString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 4,
|
||||||
|
title: 'Deadline Besok Pagi',
|
||||||
|
dueDate: DateService.now().add(1, 'day').startOf('day').toISOString(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}, [currentZone]); // Dependency: currentZone
|
||||||
|
|
||||||
|
const [currentTime, setCurrentTime] = useState<DateService>(DateService.now());
|
||||||
const [selectedDate, setSelectedDate] = useState<DateService>(DateService.now());
|
const [selectedDate, setSelectedDate] = useState<DateService>(DateService.now());
|
||||||
|
|
||||||
// 3. STATE: Khusus Demo Logic Calendar (Besok jam 00:00 vs Sekarang)
|
// State demo logic calendar
|
||||||
// Ini untuk menjawab kenapa diff kadang 0 padahal beda hari
|
const [calendarTarget, setCalendarTarget] = useState(() => DateService.now().add(1, 'day').startOf('day'));
|
||||||
const [calendarTarget] = useState(() => DateService.now().add(1, 'day').startOf('day'));
|
|
||||||
|
|
||||||
// 4. MEMO: Nilai Epoch Static (Hanya diambil saat component mount)
|
// Static date (Memo kosong) -> Akan tetap di Timezone saat pertama kali load (kecuali di-refresh)
|
||||||
// Gunakan ini jika ingin nilai 'kapan user membuka halaman'
|
// Ini bagus untuk demo bahwa object lama tidak berubah (immutable) kecuali dibuat ulang.
|
||||||
const staticDate = useMemo(() => new DateService(), []);
|
const staticDate = useMemo(() => new DateService(), []);
|
||||||
|
|
||||||
// Effect untuk update jam setiap detik
|
// Effect update jam tiap detik
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setInterval(() => {
|
const timer = setInterval(() => {
|
||||||
setCurrentTime(DateService.now());
|
setCurrentTime(DateService.now());
|
||||||
@@ -49,25 +55,79 @@ export const DateServiceComponent: React.FC = () => {
|
|||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Handler untuk tombol tambah/kurang hari
|
// --- HANDLER GANTI TIMEZONE ---
|
||||||
|
const handleZoneChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
|
const newZone = e.target.value;
|
||||||
|
setCurrentZone(newZone);
|
||||||
|
|
||||||
|
// 1. Set Global Config (Inti Perubahan)
|
||||||
|
DateService.setGlobalConfig(newZone);
|
||||||
|
|
||||||
|
// 2. Force Refresh State agar UI langsung berubah
|
||||||
|
// Kita buat instance baru agar mengambil config timezone terbaru
|
||||||
|
setCurrentTime(DateService.now());
|
||||||
|
|
||||||
|
// Kita recreate selectedDate dengan nilai raw yang sama, tapi context timezone baru
|
||||||
|
setSelectedDate((prev) => new DateService(prev.getRaw()));
|
||||||
|
|
||||||
|
// Recreate target demo calendar
|
||||||
|
setCalendarTarget(DateService.now().add(1, 'day').startOf('day'));
|
||||||
|
};
|
||||||
|
|
||||||
const handleAddDay = (days: number) => {
|
const handleAddDay = (days: number) => {
|
||||||
setSelectedDate((prev) => prev.add(days, 'day'));
|
setSelectedDate((prev) => prev.add(days, 'day'));
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-8 max-w-5xl mx-auto bg-gray-50 min-h-screen font-sans text-gray-800">
|
<div className="p-8 max-w-5xl mx-auto bg-gray-50 min-h-screen font-sans text-gray-800">
|
||||||
<h1 className="text-3xl font-bold mb-8 text-blue-900">DateService Feature Showcase</h1>
|
{/* HEADER & TIMEZONE CONTROLLER */}
|
||||||
|
<div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4 border-b border-gray-200 pb-6">
|
||||||
|
<h1 className="text-3xl font-bold text-blue-900">DateService Feature Showcase</h1>
|
||||||
|
|
||||||
|
<div className="bg-white p-3 rounded-lg shadow-sm border border-blue-100 flex items-center gap-3">
|
||||||
|
<label htmlFor="tz-switcher" className="text-xs font-bold text-gray-500 uppercase tracking-wide">
|
||||||
|
App Timezone:
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="tz-switcher"
|
||||||
|
value={currentZone}
|
||||||
|
onChange={handleZoneChange}
|
||||||
|
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 block p-1.5 outline-none font-mono"
|
||||||
|
>
|
||||||
|
{timezoneList.map((tz) => (
|
||||||
|
<option key={tz} value={tz}>
|
||||||
|
{tz}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
{/* --- CARD 1: REALTIME CLOCK --- */}
|
{/* --- CARD 1: REALTIME CLOCK --- */}
|
||||||
<div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 flex flex-col justify-between">
|
<div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 flex flex-col justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-2">Realtime Clock</h2>
|
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-2">Realtime Clock</h2>
|
||||||
<div className="text-4xl font-mono font-bold text-gray-900">{currentTime.format('HH:mm:ss')}</div>
|
|
||||||
<div className="text-lg text-gray-500 mt-1">{currentTime.format('dddd, DD MMMM YYYY')}</div>
|
<div className="flex flex-col">
|
||||||
|
<div className="text-4xl font-mono font-bold text-gray-900">{currentTime.format('HH:mm:ss')}</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 mt-2">
|
||||||
|
{/* UPDATE DI SINI: Gunakan .timezoneAbbr */}
|
||||||
|
<div className="text-sm font-bold text-blue-700 bg-blue-100 px-2 py-1 rounded border border-blue-200">
|
||||||
|
{/* Ini akan output "WIB", "WITA", atau "EST" */}
|
||||||
|
{currentTime.timezoneAbbr}
|
||||||
|
|
||||||
|
{/* Ini offset angka (+07:00) */}
|
||||||
|
<span className="opacity-60 text-xs ml-1">({currentTime.format('Z')})</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-lg text-gray-500 mt-2">{currentTime.format('dddd, DD MMMM YYYY')}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-4 text-xs bg-gray-100 p-2 rounded text-gray-500 font-mono break-all">
|
<div className="mt-4 text-xs bg-gray-100 p-2 rounded text-gray-500 font-mono break-all">
|
||||||
ISO: {currentTime.toISOString()}
|
ISO (UTC): {currentTime.toISOString()}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -79,7 +139,7 @@ export const DateServiceComponent: React.FC = () => {
|
|||||||
{/* STATIC SECTION */}
|
{/* STATIC SECTION */}
|
||||||
<div className="bg-blue-50 p-3 rounded-lg border border-blue-100">
|
<div className="bg-blue-50 p-3 rounded-lg border border-blue-100">
|
||||||
<div className="text-xs font-bold text-blue-800 mb-1">STATIC (Load Once)</div>
|
<div className="text-xs font-bold text-blue-800 mb-1">STATIC (Load Once)</div>
|
||||||
<div className="text-xs text-blue-600 mb-2">Captured via useMemo([]), tidak berubah.</div>
|
<div className="text-xs text-blue-600 mb-2">Captured on mount (keeps original timezone).</div>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||||
@@ -95,7 +155,7 @@ export const DateServiceComponent: React.FC = () => {
|
|||||||
{/* LIVE SECTION */}
|
{/* LIVE SECTION */}
|
||||||
<div className="bg-green-50 p-3 rounded-lg border border-green-100">
|
<div className="bg-green-50 p-3 rounded-lg border border-green-100">
|
||||||
<div className="text-xs font-bold text-green-800 mb-1">LIVE (Reactive)</div>
|
<div className="text-xs font-bold text-green-800 mb-1">LIVE (Reactive)</div>
|
||||||
<div className="text-xs text-green-600 mb-2">Updated every second (new instance).</div>
|
<div className="text-xs text-green-600 mb-2">Updated every second (follows dropdown).</div>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
<div className="text-[10px] uppercase text-gray-500">Epoch Millis</div>
|
||||||
@@ -110,49 +170,44 @@ export const DateServiceComponent: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* --- CARD 3: CALENDAR LOGIC DEMO (Standard vs Calendar Diff) --- */}
|
{/* --- CARD 3: CALENDAR LOGIC DEMO --- */}
|
||||||
<div className="bg-indigo-50 p-6 rounded-xl shadow-sm border border-indigo-200 md:col-span-2">
|
<div className="bg-indigo-50 p-6 rounded-xl shadow-sm border border-indigo-200 md:col-span-2">
|
||||||
<h2 className="text-lg font-bold text-indigo-900 mb-4 flex items-center gap-2">
|
<h2 className="text-lg font-bold text-indigo-900 mb-4 flex items-center gap-2">
|
||||||
🗓️ Calendar Logic Demo (The "Zero Day" Issue)
|
🗓️ Calendar Logic Demo (The "Zero Day" Issue)
|
||||||
</h2>
|
</h2>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||||
{/* Info Section */}
|
|
||||||
<div className="text-sm text-indigo-800 space-y-2">
|
<div className="text-sm text-indigo-800 space-y-2">
|
||||||
<p>
|
<p>
|
||||||
Compare <strong>Current Time</strong> vs <strong>Tomorrow 00:00</strong>.
|
Compare <strong>Current Time</strong> vs <strong>Tomorrow 00:00</strong>.
|
||||||
</p>
|
</p>
|
||||||
<div className="bg-white/50 p-2 rounded">
|
<div className="bg-white/50 p-2 rounded">
|
||||||
<div className="flex justify-between text-xs">
|
<div className="flex justify-between text-xs">
|
||||||
<span>Now:</span>
|
<span>Now ({currentZone}):</span>
|
||||||
<span className="font-mono font-bold">{currentTime.format('HH:mm')}</span>
|
<span className="font-mono font-bold">{currentTime.format('HH:mm')}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between text-xs mt-1">
|
<div className="flex justify-between text-xs mt-1">
|
||||||
<span>Target:</span>
|
<span>Target (Start of Day):</span>
|
||||||
<span className="font-mono font-bold">{calendarTarget.format('DD MMM HH:mm')}</span>
|
<span className="font-mono font-bold">{calendarTarget.format('DD MMM HH:mm')}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Wrong Way */}
|
|
||||||
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-red-400">
|
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-red-400">
|
||||||
<div className="text-xs text-gray-400 uppercase font-bold">Standard .diff('day')</div>
|
<div className="text-xs text-gray-400 uppercase font-bold">Standard .diff('day')</div>
|
||||||
<div className="text-2xl font-bold text-red-600 mt-1">
|
<div className="text-2xl font-bold text-red-600 mt-1">
|
||||||
{calendarTarget.diff(currentTime, 'day')}{' '}
|
{calendarTarget.diff(currentTime, 'day')}{' '}
|
||||||
<span className="text-sm font-normal text-gray-500">Days</span>
|
<span className="text-sm font-normal text-gray-500">Days</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-red-500 mt-1">
|
<p className="text-xs text-red-500 mt-1">Hasil 0 jika jarak < 24 jam.</p>
|
||||||
Hasil 0 jika jarak < 24 jam. Kurang cocok untuk deadline "H-1".
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right Way */}
|
|
||||||
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-green-500">
|
<div className="bg-white p-4 rounded-lg shadow-sm border-l-4 border-green-500">
|
||||||
<div className="text-xs text-gray-400 uppercase font-bold">New .diffCalendarDay()</div>
|
<div className="text-xs text-gray-400 uppercase font-bold">New .diffCalendarDay()</div>
|
||||||
<div className="text-2xl font-bold text-green-600 mt-1">
|
<div className="text-2xl font-bold text-green-600 mt-1">
|
||||||
{calendarTarget.diffCalendarDay(currentTime)}{' '}
|
{calendarTarget.diffCalendarDay(currentTime)}{' '}
|
||||||
<span className="text-sm font-normal text-gray-500">Days</span>
|
<span className="text-sm font-normal text-gray-500">Days</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-green-600 mt-1">Hasil 1. Menghitung selisih tanggal kalender (ignore jam).</p>
|
<p className="text-xs text-green-600 mt-1">Hasil 1. Benar secara kalender.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -174,6 +229,7 @@ export const DateServiceComponent: React.FC = () => {
|
|||||||
<div className="flex-1 text-center">
|
<div className="flex-1 text-center">
|
||||||
<span className="block text-3xl font-bold text-blue-900">{selectedDate.format('DD MMMM YYYY')}</span>
|
<span className="block text-3xl font-bold text-blue-900">{selectedDate.format('DD MMMM YYYY')}</span>
|
||||||
<span className="text-sm text-blue-600 font-medium">Selected Date State</span>
|
<span className="text-sm text-blue-600 font-medium">Selected Date State</span>
|
||||||
|
<span className="text-xs text-gray-400 block mt-1">Offset: {selectedDate.format('Z')}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
@@ -201,9 +257,11 @@ export const DateServiceComponent: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* --- CARD 5: TASK LIST (IMPLEMENTATION REAL) --- */}
|
{/* --- CARD 5: TASK LIST (DYNAMIC) --- */}
|
||||||
<div className="mt-8 bg-white p-6 rounded-xl shadow-sm border border-gray-200">
|
<div className="mt-8 bg-white p-6 rounded-xl shadow-sm border border-gray-200">
|
||||||
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">Task List Implementation</h2>
|
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">
|
||||||
|
Task List Implementation (Timezone Aware)
|
||||||
|
</h2>
|
||||||
|
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full text-left border-collapse">
|
<table className="w-full text-left border-collapse">
|
||||||
@@ -212,22 +270,16 @@ export const DateServiceComponent: React.FC = () => {
|
|||||||
<th className="py-3 px-4 rounded-tl-lg">Task Name</th>
|
<th className="py-3 px-4 rounded-tl-lg">Task Name</th>
|
||||||
<th className="py-3 px-4">Due Date</th>
|
<th className="py-3 px-4">Due Date</th>
|
||||||
<th className="py-3 px-4">Status Badge</th>
|
<th className="py-3 px-4">Status Badge</th>
|
||||||
<th className="py-3 px-4 rounded-tr-lg">Human Readable Countdown</th>
|
<th className="py-3 px-4 rounded-tr-lg">Countdown</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{MOCK_TASKS.map((task) => {
|
{tasks.map((task) => {
|
||||||
const dueDate = new DateService(task.dueDate);
|
const dueDate = new DateService(task.dueDate);
|
||||||
const now = DateService.now(); // Mengambil waktu 'live' dari state currentTime akan menyebabkan re-render tiap detik, tapi disini kita instantiate baru agar logic per baris bersih.
|
const now = DateService.now();
|
||||||
|
|
||||||
// Logic 1: Apakah sudah lewat? (Check absolute timestamp)
|
|
||||||
const isOverdue = now.isAfter(dueDate);
|
const isOverdue = now.isAfter(dueDate);
|
||||||
|
|
||||||
// Logic 2: Gunakan CALENDAR DIFF untuk countdown yang enak dibaca user
|
|
||||||
// Jika pakai diff() biasa, tugas besok pagi bisa dianggap '0 days left'
|
|
||||||
const daysDiff = dueDate.diffCalendarDay(now);
|
const daysDiff = dueDate.diffCalendarDay(now);
|
||||||
|
|
||||||
// Logic 3: Warning jika kurang dari 3 hari lagi (dan belum overdue)
|
|
||||||
const isDueSoon = !isOverdue && daysDiff <= 3;
|
const isDueSoon = !isOverdue && daysDiff <= 3;
|
||||||
|
|
||||||
let statusBadge;
|
let statusBadge;
|
||||||
@@ -256,11 +308,14 @@ export const DateServiceComponent: React.FC = () => {
|
|||||||
return (
|
return (
|
||||||
<tr key={task.id} className={rowClass}>
|
<tr key={task.id} className={rowClass}>
|
||||||
<td className="py-3 px-4 font-medium text-gray-700">{task.title}</td>
|
<td className="py-3 px-4 font-medium text-gray-700">{task.title}</td>
|
||||||
<td className="py-3 px-4 text-gray-500 font-mono text-sm">{dueDate.format('DD MMM YYYY HH:mm')}</td>
|
<td className="py-3 px-4 text-gray-500 font-mono text-sm">
|
||||||
|
{dueDate.format('DD MMM YYYY HH:mm')}
|
||||||
|
<span className="text-[10px] text-gray-400 ml-1">{dueDate.format('Z')}</span>
|
||||||
|
</td>
|
||||||
<td className="py-3 px-4">{statusBadge}</td>
|
<td className="py-3 px-4">{statusBadge}</td>
|
||||||
<td className="py-3 px-4 text-sm text-gray-600 font-medium">
|
<td className="py-3 px-4 text-sm text-gray-600 font-medium">
|
||||||
{isOverdue ? (
|
{isOverdue ? (
|
||||||
`${Math.abs(daysDiff)} days late` // Gunakan Math.abs karena diff negatif
|
`${Math.abs(daysDiff)} days late`
|
||||||
) : daysDiff === 0 ? (
|
) : daysDiff === 0 ? (
|
||||||
<span className="text-amber-600">Today!</span>
|
<span className="text-amber-600">Today!</span>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -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 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.
|
* Accepted input formats for DateService.
|
||||||
* Ini memberitahu TS bahwa input boleh berupa string, date, atau object Dayjs itu sendiri.
|
|
||||||
*/
|
*/
|
||||||
export type DateInput = string | number | Date | Dayjs | null | undefined;
|
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 {
|
interface IDateManager {
|
||||||
format(formatString?: string): string;
|
format(format?: string): string;
|
||||||
add(value: number, unit: TimeUnit): IDateManager;
|
add(value: number, unit: TimeUnit): IDateManager;
|
||||||
subtract(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;
|
isBefore(date: DateInput | DateService): boolean;
|
||||||
isAfter(date: DateInput | DateService): boolean;
|
isAfter(date: DateInput | DateService): boolean;
|
||||||
isSame(date: DateInput | DateService, unit?: TimeUnit): boolean;
|
isSame(date: DateInput | DateService, unit?: TimeUnit): boolean;
|
||||||
diff(date: DateInput | DateService, unit: TimeUnit, precise?: boolean): number;
|
diff(date: DateInput | DateService, unit: TimeUnit, precise?: boolean): number;
|
||||||
|
diffCalendarDay(date: DateInput | DateService): number;
|
||||||
toISOString(): string;
|
|
||||||
toDate(): Date;
|
|
||||||
startOf(unit: TimeUnit): IDateManager;
|
startOf(unit: TimeUnit): IDateManager;
|
||||||
endOf(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 {
|
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;
|
private readonly _date: Dayjs;
|
||||||
|
|
||||||
constructor(date?: DateInput | DateService) {
|
/**
|
||||||
// FIX: Handle jika inputnya adalah instance dari DateService lain
|
* Global default timezone.
|
||||||
if (date instanceof DateService) {
|
* Used by all DateService instances.
|
||||||
this._date = date.getRaw();
|
*/
|
||||||
} else {
|
private static _defaultTimezone: string = dayjs.tz.guess();
|
||||||
this._date = dayjs(date);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this._date.isValid()) {
|
/* ----------------------------------------------------------------
|
||||||
console.warn(`[DateService] Invalid date: ${date}. Fallback to now.`);
|
* Global Configuration
|
||||||
this._date = dayjs();
|
* ---------------------------------------------------------------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
* Get the currently active global timezone.
|
||||||
return this._date;
|
*/
|
||||||
|
static getGlobalTimezone(): string {
|
||||||
|
return DateService._defaultTimezone;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a DateService instance representing the current moment.
|
||||||
|
*/
|
||||||
static now(): DateService {
|
static now(): DateService {
|
||||||
return new DateService();
|
return new DateService();
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Implementation Methods ---
|
/* ----------------------------------------------------------------
|
||||||
|
* Constructor
|
||||||
|
* ---------------------------------------------------------------- */
|
||||||
|
|
||||||
format(formatString: string = 'YYYY-MM-DD'): string {
|
constructor(date?: DateInput | DateService) {
|
||||||
return this._date.format(formatString);
|
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 {
|
add(value: number, unit: TimeUnit): DateService {
|
||||||
return new DateService(this._date.add(value, unit as ManipulateType));
|
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));
|
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 {
|
startOf(unit: TimeUnit): DateService {
|
||||||
return new DateService(this._date.startOf(unit as OpUnitType));
|
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));
|
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 {
|
isAfter(date: DateInput | DateService): boolean {
|
||||||
return this._date.toDate();
|
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 {
|
get timestamp(): number {
|
||||||
return this._date.valueOf();
|
return this._date.valueOf();
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Mengembalikan Epoch dalam Milliseconds (13 digit).
|
|
||||||
* Contoh: 1704067200000
|
|
||||||
* Gunakan ini untuk kalkulasi di Frontend JS/TS.
|
|
||||||
*/
|
|
||||||
get epochMillis(): number {
|
get epochMillis(): number {
|
||||||
return this._date.valueOf();
|
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 {
|
get epochSeconds(): number {
|
||||||
return this._date.unix();
|
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