Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(table): render date columns all-numeric with a four-digit year
Elian Doran8b36e33523f1
diff --git a/apps/client/src/utils/formatters.spec.ts b/apps/client/src/utils/formatters.spec.tsindex 72417f4b6e..4883a9864c 100644--- a/apps/client/src/utils/formatters.spec.ts+++ b/apps/client/src/utils/formatters.spec.ts@@ -7,8 +7,10 @@ vi.mock("../services/i18n", () => ({t: (key: string, opts?: { count?: number }) => `${key}|${opts?.count}`}));+import { LOCALES } from "@triliumnext/commons";+import options from "../services/options";-import { formatDateTime, formatDuration, normalizeLocale } from "./formatters";+import { formatDateNumeric, formatDateTime, formatDuration, normalizeLocale } from "./formatters";describe("formatters", () => {it("tolerates incorrect locale", () => {@@ -94,6 +96,63 @@ describe("formatters", () => {expect(() => formatDateTime(new Date(), "none", "none")).toThrow("Incorrect state.");});+ describe("formatDateNumeric", () => {+ // Every locale the user can actually pick as a formatting locale, which is the set that+ // declares an electronLocale (see the options page).+ const FORMATTING_LOCALES = LOCALES.filter((locale) => locale.electronLocale);++ it("renders an all-numeric, four-digit-year date in every selectable formatting locale", () => {+ expect(FORMATTING_LOCALES.length).toBeGreaterThan(0);++ for (const locale of FORMATTING_LOCALES) {+ options.set("formattingLocale", locale.id);+ const formatted = formatDateNumeric("2026-01-31");++ // The two things a dateStyle preset could not guarantee across locales: "short"+ // yields a two-digit year in some ("31.01.26" in German), and "medium" spells the+ // month out in others ("Jan 31, 2026" in US English).+ expect(formatted, locale.id).toContain("2026");+ expect(formatted, locale.id).not.toMatch(/\p{L}/u);+ }+ });++ it("formats the reported German case as DD.MM.YYYY", () => {+ options.set("formattingLocale", "de");++ expect(formatDateNumeric("2026-01-31")).toBe("31.01.2026");+ expect(formatDateNumeric("2026-01-31T14:05", true)).toBe("31.01.2026, 14:05");+ });++ it("pads a single-digit hour in 24-hour locales but not in 12-hour ones", () => {+ // A fixed hour option gets one of these wrong: "numeric" renders German as "2:05",+ // "2-digit" renders US English as "02:05 AM".+ options.set("formattingLocale", "de");+ expect(formatDateNumeric("2026-01-31T02:05", true)).toBe("31.01.2026, 02:05");+ expect(formatDateNumeric("2026-01-31T14:05", true)).toBe("31.01.2026, 14:05");++ options.set("formattingLocale", "ja");+ expect(formatDateNumeric("2026-01-31T02:05", true)).toBe("2026/01/31 02:05");++ options.set("formattingLocale", "en");+ // Normalized because ICU 72+ separates the day period with U+202F rather than a space.+ expect(formatDateNumeric("2026-01-31T02:05", true).replace(/\s/g, " ")).toBe("01/31/2026, 2:05 AM");+ expect(formatDateNumeric("2026-01-31T14:05", true).replace(/\s/g, " ")).toBe("01/31/2026, 2:05 PM");+ });++ it("falls back to the default locale when the configured one is unusable", () => {+ // The dev-only "en_rtl" normalizes to "en-rtl", which Intl rejects outright.+ options.set("formattingLocale", "en_rtl");++ expect(formatDateNumeric("2026-01-31")).toContain("2026");+ });++ it("returns an empty string for falsy dates", () => {+ expect(formatDateNumeric(null)).toBe("");+ expect(formatDateNumeric(undefined)).toBe("");+ expect(formatDateNumeric("")).toBe("");+ });+ });+describe("formatDuration", () => {it("reports the value in the unit the user picked, for every time scale", () => {expect(formatDuration(30, 1)).toBe("time_interval.seconds|30");diff --git a/apps/client/src/utils/formatters.ts b/apps/client/src/utils/formatters.tsindex bb8677516c..99d748bd20 100644--- a/apps/client/src/utils/formatters.ts+++ b/apps/client/src/utils/formatters.ts@@ -54,29 +54,8 @@ export function formatDateTime(date: string | Date | number | null | undefined,return "";}- const locale = normalizeLocale(options.get("formattingLocale") || options.get("locale") || navigator.language);-- let parsedDate: Date;- if (typeof date === "string" || typeof date === "number") {- const dateOnlyMatch = typeof date === "string" && /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);- if (dateOnlyMatch) {- // A date-only string ("YYYY-MM-DD") is parsed as UTC midnight by the Date- // constructor, so it rolls back to the previous day when displayed in a- // negative UTC offset (e.g. the Recent Changes date headers). Treat it as a- // local calendar date so the same day is shown regardless of timezone.- const [ , year, month, day ] = dateOnlyMatch;- parsedDate = new Date(Number(year), Number(month) - 1, Number(day));- } else {- // Parse the given string as a date- parsedDate = new Date(date);- }- } else if (date instanceof Date) {- // The given date is already a Date instance or a number- parsedDate = date;- } else {- // Invalid type- throw new TypeError(`Invalid type for the "date" argument.`);- }+ const locale = getFormattingLocale();+ const parsedDate = parseDate(date);if (timeStyle !== "none" && dateStyle !== "none") {// Format the date and time@@ -106,6 +85,84 @@ export function formatDateTime(date: string | Date | number | null | undefined,throw new Error("Incorrect state.");}+/**+ * Formats the given date with all-numeric components and a four-digit year, e.g. "31.01.2026" in+ * German or "01/31/2026" in US English. The locale still decides field order and separators.+ *+ * The `dateStyle` presets cannot express this. They map to each locale's CLDR patterns, which are+ * authored per locale: "short" drops to a two-digit year in some locales (`31.01.26` in German) but+ * not others (`31/01/2026` in French), and "medium" spells the month out in some (`Jan 31, 2026`)+ * while staying numeric in others. Prefer this where a compact, unambiguous and locale-consistent+ * date matters, such as a table column, and `formatDateTime()` for prose.+ *+ * @param withTime also renders the time, for values that carry one.+ */+export function formatDateNumeric(date: string | Date | number | null | undefined, withTime = false) {+ if (!date) {+ return "";+ }++ const locale = getFormattingLocale();+ const parsedDate = parseDate(date);+ const formatOptions: Intl.DateTimeFormatOptions = { year: "numeric", month: "2-digit", day: "2-digit" };+ if (withTime) {+ // Pad the hour the way the locale's own short time pattern does: a 24-hour locale writes+ // "02:05", a 12-hour one "2:05 AM". Either fixed choice is wrong somewhere, and `timeStyle`+ // -- which would get both right -- cannot be combined with explicit date components.+ formatOptions.hour = is12HourLocale(locale) ? "numeric" : "2-digit";+ formatOptions.minute = "2-digit";+ }++ try {+ return new Intl.DateTimeFormat(locale, formatOptions).format(parsedDate);+ } catch (e) {+ // An unusable locale (e.g. the dev-only "en_rtl", which normalizes to the invalid "en-rtl")+ // makes the constructor throw; fall back to the environment default.+ return new Intl.DateTimeFormat(undefined, formatOptions).format(parsedDate);+ }+}++function is12HourLocale(locale: string) {+ try {+ return isTwelveHourCycle(new Intl.DateTimeFormat(locale, { hour: "numeric" }));+ } catch (e) {+ // Same unusable-locale fallback as the caller, so both agree on which cycle is in play.+ return isTwelveHourCycle(new Intl.DateTimeFormat(undefined, { hour: "numeric" }));+ }+}++function isTwelveHourCycle(formatter: Intl.DateTimeFormat) {+ const { hourCycle } = formatter.resolvedOptions();+ return hourCycle === "h11" || hourCycle === "h12";+}++function getFormattingLocale() {+ return normalizeLocale(options.get("formattingLocale") || options.get("locale") || navigator.language);+}++function parseDate(date: string | Date | number): Date {+ if (typeof date === "string" || typeof date === "number") {+ const dateOnlyMatch = typeof date === "string" && /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);+ if (dateOnlyMatch) {+ // A date-only string ("YYYY-MM-DD") is parsed as UTC midnight by the Date+ // constructor, so it rolls back to the previous day when displayed in a+ // negative UTC offset (e.g. the Recent Changes date headers). Treat it as a+ // local calendar date so the same day is shown regardless of timezone.+ const [ , year, month, day ] = dateOnlyMatch;+ return new Date(Number(year), Number(month) - 1, Number(day));+ }++ // Parse the given string as a date+ return new Date(date);+ } else if (date instanceof Date) {+ // The given date is already a Date instance or a number+ return date;+ }++ // Invalid type+ throw new TypeError(`Invalid type for the "date" argument.`);+}+export function normalizeLocale(locale: string) {locale = locale.replaceAll("_", "-");switch (locale) {diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.tsindex 8624fd27eb..75ac1e8ba5 100644--- a/apps/client/src/widgets/collections/table/columns.spec.ts+++ b/apps/client/src/widgets/collections/table/columns.spec.ts@@ -138,28 +138,28 @@ describe("formatLabelDate", () => {it("renders dates and datetimes in the configured formatting locale", () => {options.set("formattingLocale", "de");- expect(formatLabelDate("2026-01-31", "none")).toBe("31.01.26");- expect(formatLabelDate("2026-01-31T14:05", "short")).toBe("31.01.26, 14:05");+ expect(formatLabelDate("2026-01-31", false)).toBe("31.01.2026");+ expect(formatLabelDate("2026-01-31T14:05", true)).toBe("31.01.2026, 14:05");});it("keeps a date-only value on its calendar day rather than shifting it by timezone", () => {options.set("formattingLocale", "de");// Parsed as UTC midnight, "2026-01-31" would roll back a day in a negative UTC offset.- expect(formatLabelDate("2026-01-31", "none")).toBe("31.01.26");+ expect(formatLabelDate("2026-01-31", false)).toBe("31.01.2026");});it("echoes values that are not dates instead of throwing inside the grid render", () => {options.set("formattingLocale", "de");// Intl throws a RangeError on an invalid date, which would break the whole table.- expect(formatLabelDate("not a date", "short")).toBe("not a date");- expect(formatLabelDate("not a date", "none")).toBe("not a date");+ expect(formatLabelDate("not a date", true)).toBe("not a date");+ expect(formatLabelDate("not a date", false)).toBe("not a date");});it("renders a blank cell for missing values", () => {- expect(formatLabelDate(undefined, "none")).toBe("");- expect(formatLabelDate(null, "short")).toBe("");- expect(formatLabelDate("", "none")).toBe("");+ expect(formatLabelDate(undefined, false)).toBe("");+ expect(formatLabelDate(null, true)).toBe("");+ expect(formatLabelDate("", false)).toBe("");});});diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsxindex fe40aff133..bf4ca831bc 100644--- a/apps/client/src/widgets/collections/table/columns.tsx+++ b/apps/client/src/widgets/collections/table/columns.tsx@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from "preact/hooks";import type { CellComponent, ColumnDefinition, EmptyCallback, FormatterParams, RowComponent, ValueBooleanCallback, ValueVoidCallback } from "tabulator-tables";import froca from "../../../services/froca.js";-import { formatDateTime } from "../../../utils/formatters.js";+import { formatDateNumeric } from "../../../utils/formatters.js";import Icon from "../../react/Icon.jsx";import NoteAutocomplete from "../../react/NoteAutocomplete.jsx";import { renderReactWidget } from "../../react/react_utils.jsx";@@ -39,11 +39,11 @@ const labelTypeMappings: Record<ColumnType, Partial<ColumnDefinition>> = {date: {editor: "date",// Values are stored as ISO ("YYYY-MM-DD"), which Tabulator would otherwise render as-is.- formatter: (cell) => formatLabelDate(cell.getValue(), "none")+ formatter: (cell) => formatLabelDate(cell.getValue(), false)},datetime: {editor: "datetime",- formatter: (cell) => formatLabelDate(cell.getValue(), "short")+ formatter: (cell) => formatLabelDate(cell.getValue(), true)},number: {editor: "number",@@ -72,19 +72,20 @@ const labelTypeMappings: Record<ColumnType, Partial<ColumnDefinition>> = {};/**- * Renders a stored date label through the user's formatting locale.+ * Renders a stored date label through the user's formatting locale, all-numeric so that columns stay+ * narrow and every locale shows a four-digit year.** Unparseable values are echoed back rather than formatted: label values are free text, so a* date-typed column can hold anything a user typed, imported, or left behind by retyping a text* label as a date. `Intl.DateTimeFormat` throws a `RangeError` on an invalid date, and since this* runs inside a Tabulator formatter, that would take down the whole grid rather than one cell.*/-export function formatLabelDate(value: unknown, timeStyle: "none" | "short") {+export function formatLabelDate(value: unknown, withTime: boolean) {if (typeof value !== "string" || !value) return "";- // Passed as a string so that formatDateTime() keeps its date-only ("YYYY-MM-DD") handling,+ // Passed as a string so that formatDateNumeric() keeps its date-only ("YYYY-MM-DD") handling,// which pins the value to the local calendar day instead of shifting it across timezones.if (Number.isNaN(new Date(value).getTime())) return value;- return formatDateTime(value, "short", timeStyle);+ return formatDateNumeric(value, withTime);}interface BuildColumnArgs {