Add date helpers

This commit is contained in:
iamdoubz committed 2026-11-05 16:08:37 -06:00
1 parent 2451a28e25
commit 886a4d8a61
1 file changed
+76
+76
View File
@@ -0,0 +1,76 @@
// Dates travel as 'YYYY-MM-DD' strings and are shown in the device's language.
export function parse(d: string): Date {
const [y, m, day] = d.split('-').map(Number);
return new Date(y, m - 1, day);
}
export function iso(d: Date): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
export function dayLabel(d: string): string {
return parse(d).toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' });
}
export function monthLabel(month: string): string {
return parse(month + '-01').toLocaleDateString(undefined, { month: 'long', year: 'numeric' });
}
export function shiftMonth(month: string, by: number): string {
const d = parse(month + '-01');
d.setMonth(d.getMonth() + by);
return iso(d).slice(0, 7);
}
export function thisMonth(): string {
return iso(new Date()).slice(0, 7);
}
export function monthEnd(month: string): string {
const d = parse(month + '-01');
d.setMonth(d.getMonth() + 1, 0);
return iso(d);
}
export function timeLabel(t: string | null): string {
if (!t) return '';
const [h, m] = t.split(':').map(Number);
return new Date(2000, 0, 1, h, m).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
}
export function whenLabel(e: { date: string; end_date: string | null; all_day: boolean; start_time: string | null; end_time: string | null }): string {
let s = dayLabel(e.date);
if (e.end_date && e.end_date !== e.date) s += ` – ${dayLabel(e.end_date)}`;
if (!e.all_day && e.start_time) s += `, ${timeLabel(e.start_time)}${e.end_time ? `–${timeLabel(e.end_time)}` : ''}`;
return s;
}
/** Weeks (arrays of 7 dates, Sunday first) covering a month. */
export function monthWeeks(month: string): string[][] {
const first = parse(month + '-01');
const start = new Date(first);
start.setDate(1 - first.getDay());
const weeks: string[][] = [];
const d = new Date(start);
do {
const week: string[] = [];
for (let i = 0; i < 7; i++) {
week.push(iso(d));
d.setDate(d.getDate() + 1);
}
weeks.push(week);
} while (d.getMonth() === first.getMonth());
return weeks;
}
/** Months (YYYY-MM) between two dates, inclusive. */
export function monthsBetween(start: string, end: string): string[] {
const out: string[] = [];
let m = start.slice(0, 7);
while (m <= end.slice(0, 7) && out.length < 24) {
out.push(m);
m = shiftMonth(m, 1);
}
return out;
}