Introduce a locale/12-hour/24-hour preference on the clock service and a shared Intl-based formatter used across the dashboard.
50 lines
1.5 KiB
JavaScript
50 lines
1.5 KiB
JavaScript
// Shared time formatting for the clock and calendar widgets. The stored
|
|
// preference picks between the system locale's convention, 12-hour, and
|
|
// 24-hour; everything goes through Intl so the separators and day periods match
|
|
// the locale.
|
|
|
|
export const DEFAULT_TIME_FORMAT = 'locale';
|
|
|
|
export const TIME_FORMATS = [
|
|
{ value: 'locale', label: 'Match system' },
|
|
{ value: '12h', label: '12-hour' },
|
|
{ value: '24h', label: '24-hour' },
|
|
];
|
|
|
|
const OPTIONS = {
|
|
locale: { hour: 'numeric', minute: '2-digit' },
|
|
'12h': { hour: 'numeric', minute: '2-digit', hour12: true },
|
|
'24h': { hour: '2-digit', minute: '2-digit', hour12: false },
|
|
};
|
|
|
|
export function timeOptions(format) {
|
|
return OPTIONS[format] ?? OPTIONS[DEFAULT_TIME_FORMAT];
|
|
}
|
|
|
|
// The full time string, e.g. `1:05 PM` (12h) or `13:05` (24h).
|
|
export function formatTime(date, format = DEFAULT_TIME_FORMAT) {
|
|
return new Intl.DateTimeFormat(undefined, timeOptions(format)).format(date);
|
|
}
|
|
|
|
// Splits the time into the clock face and its day period, so the clock can
|
|
// render the period smaller. `period` is empty for 24-hour formats.
|
|
export function timeParts(date, format = DEFAULT_TIME_FORMAT) {
|
|
const parts = new Intl.DateTimeFormat(
|
|
undefined,
|
|
timeOptions(format)
|
|
).formatToParts(date);
|
|
|
|
let time = '';
|
|
let period = '';
|
|
|
|
for (const part of parts) {
|
|
if (part.type === 'dayPeriod') {
|
|
period = part.value;
|
|
} else {
|
|
time += part.value;
|
|
}
|
|
}
|
|
|
|
return { time: time.trim(), period };
|
|
}
|