-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtime-format.ts
More file actions
39 lines (34 loc) · 1.4 KB
/
time-format.ts
File metadata and controls
39 lines (34 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Weather and clock formatting utilities
*/
const timeFormatterByLocale = new Map<string, Intl.DateTimeFormat>();
function getTimeFormatter(locale: string, use24HourTime = false): Intl.DateTimeFormat {
const formatterKey = `${locale}:${use24HourTime ? '24' : '12'}`;
const existing = timeFormatterByLocale.get(formatterKey);
if (existing) {
return existing;
}
const formatter = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: '2-digit',
hour12: !use24HourTime,
});
timeFormatterByLocale.set(formatterKey, formatter);
return formatter;
}
export function formatClock(value: unknown, locale: string, use24HourTime = false): string {
if (typeof value !== 'string' || !value) return '--';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return getTimeFormatter(locale, use24HourTime).format(date);
}
export function formatDaylight(sunrise: unknown, sunset: unknown): string {
if (typeof sunrise !== 'string' || typeof sunset !== 'string') return '--';
const sunriseDate = new Date(sunrise);
const sunsetDate = new Date(sunset);
if (Number.isNaN(sunriseDate.getTime()) || Number.isNaN(sunsetDate.getTime())) return '--';
const diffMs = Math.max(0, sunsetDate.getTime() - sunriseDate.getTime());
const hours = Math.floor(diffMs / 3_600_000);
const minutes = Math.round((diffMs % 3_600_000) / 60_000);
return `${hours} h ${minutes} m`;
}