Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

dates.ts

66 lines2.4 KB

1const DAY_MS = 24 * 60 * 60 * 1000;
2​
3const timeFormat = new Intl.DateTimeFormat("en-GB", { hour: "2-digit", minute: "2-digit" });
4const weekdayFormat = new Intl.DateTimeFormat("en-GB", { weekday: "long" });
5const shortDateFormat = new Intl.DateTimeFormat("en-GB", {
6 day: "2-digit",
7 month: "2-digit",
8 year: "numeric",
9});
10const monthFormat = new Intl.DateTimeFormat("en-GB", { month: "long" });
11const longDateFormat = new Intl.DateTimeFormat("en-GB", {
12 day: "numeric",
13 month: "long",
14 year: "numeric",
15});
16​
17function startOfDay(date: Date): number {
18 return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
20​
21/** Whole calendar days between `date` and `now` (0 = today, 1 = yesterday…). */
22export function daysAgo(date: Date, now: Date): number {
23 return Math.round((startOfDay(now) - startOfDay(date)) / DAY_MS);
25​
26/** Section headers in the note list, the way Apple Notes groups by date. */
27export function dateGroupLabel(date: Date, now: Date): string {
28 const days = daysAgo(date, now);
29 if (days <= 0) return "Today";
30 if (days === 1) return "Yesterday";
31 if (days < 7) return "Previous 7 Days";
32 if (days < 30) return "Previous 30 Days";
33 if (date.getFullYear() === now.getFullYear()) return monthFormat.format(date);
34 return String(date.getFullYear());
36​
37/** The short date shown before a note's snippet: "20:35", "Yesterday", "Monday", "12/09/2026". */
38export function formatListDate(date: Date, now: Date): string {
39 const days = daysAgo(date, now);
40 if (days <= 0) return timeFormat.format(date);
41 if (days === 1) return "Yesterday";
42 if (days < 7) return weekdayFormat.format(date);
43 return shortDateFormat.format(date);
45​
46/** The grey, centred timestamp at the top of the editor. */
47export function formatEditorDate(date: Date): string {
48 return `${longDateFormat.format(date)} at ${timeFormat.format(date)}`;
50​
51export interface DateGroup<T> {
52 label: string;
53 items: T[];
55​
56/** Groups items (already sorted newest first) into consecutive date sections. */
57export function groupByDate<T>(items: T[], getDate: (item: T) => Date, now: Date): DateGroup<T>[] {
58 const groups: DateGroup<T>[] = [];
59 for (const item of items) {
60 const label = dateGroupLabel(getDate(item), now);
61 const current = groups.at(-1);
62 if (current?.label === label) current.items.push(item);
63 else groups.push({ label, items: [item] });
64 }
65 return groups;