Files
Nilai_Clock/src/utils/time.js
T
2025-11-03 16:48:13 +08:00

51 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// src/utils/time.js
// Same logic as apiFetch and KillSwitchManagement
export function getUserTimezone() {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Kuala_Lumpur';
} catch {
return 'Asia_Kuala_Lumpur';
}
}
// utcValue can be: "2025-11-03 16:30:00", ISO string, or Date
export function formatUtcToLocal(utcValue, options = {}) {
if (!utcValue) return '';
const tz = options.timeZone || getUserTimezone();
const locale = options.locale || 'en-MY';
let d;
if (utcValue instanceof Date) {
d = utcValue;
} else if (typeof utcValue === 'string') {
// Normalize: DB gives "YYYY-MM-DD HH:mm:ss" (UTC) turn into ISO UTC
let iso = utcValue;
if (!iso.endsWith('Z')) {
if (iso.includes('T')) {
iso = iso + 'Z';
} else {
iso = iso.replace(' ', 'T') + 'Z';
}
}
d = new Date(iso);
} else if (typeof utcValue === 'number') {
d = new Date(utcValue);
} else {
return '';
}
return d.toLocaleString(locale, {
timeZone: tz,
year: options.year ?? 'numeric',
month: options.month ?? '2-digit',
day: options.day ?? '2-digit',
hour: options.hour ?? '2-digit',
minute: options.minute ?? '2-digit',
second: options.second ?? '2-digit',
hour12: options.hour12 ?? false,
});
}