A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: apply column format to datetime cells in tables (#11326)
Kiran Gadhavedd19ff02b0ab
diff --git a/frontend/src/components/data-table/__tests__/column_formatting.test.ts b/frontend/src/components/data-table/__tests__/column_formatting.test.tsindex d7cd6fe5d1..428287bc07 100644--- a/frontend/src/components/data-table/__tests__/column_formatting.test.ts+++ b/frontend/src/components/data-table/__tests__/column_formatting.test.ts@@ -50,6 +50,36 @@ describe("applyFormat", () => {}),).toBe("10/1/23, 12:00:00 PM UTC");});++ it("should treat naive datetime strings as UTC", () => {+ const naive = "2023-10-01 23:30:00";+ expect(+ applyFormat(naive, { locale, format: "Date", dataType: "datetime" }),+ ).toBe("10/1/23");+ expect(+ applyFormat(naive, {+ locale,+ format: "Datetime",+ dataType: "datetime",+ }),+ ).toBe("10/1/23, 11:30:00 PM UTC");+ expect(+ applyFormat(naive, { locale, format: "Time", dataType: "datetime" }),+ ).toBe("11:30:00 PM UTC");+ expect(+ applyFormat("2023-10-01T23:30:00.250", {+ locale,+ format: "Time",+ dataType: "datetime",+ }),+ ).toBe("11:30:00 PM UTC");+ });++ it("should keep the calendar date for date-only strings", () => {+ expect(+ applyFormat("2023-10-01", { locale, format: "Date", dataType: "date" }),+ ).toBe("10/1/23");+ });});describe("number formatting", () => {diff --git a/frontend/src/components/data-table/__tests__/columns.test.tsx b/frontend/src/components/data-table/__tests__/columns.test.tsxindex b77d62f5d1..70fe0acfad 100644--- a/frontend/src/components/data-table/__tests__/columns.test.tsx+++ b/frontend/src/components/data-table/__tests__/columns.test.tsx@@ -1268,6 +1268,76 @@ describe("renderCellValue with datetime values", () => {}).not.toThrow();});});++ it("should render the column format for datetime strings", () => {+ const mockColumn = {+ ...createMockColumn(),+ getColumnFormatting: () => "Date",+ applyColumnFormatting: () => "FORMATTED",+ } as unknown as Column<unknown>;++ const selectCell = vi.fn();+ const result = renderCellValue({+ column: mockColumn,+ renderValue: () => "2024-06-14 12:34:20",+ getValue: () => "2024-06-14 12:34:20",+ selectCell,+ cellStyles: "cell-styles",+ });+ const { container } = render(+ <I18nProvider locale="en-US">+ <TooltipProvider>{result}</TooltipProvider>+ </I18nProvider>,+ );+ expect(container.textContent).toContain("FORMATTED");+ expect(container.textContent).not.toContain("2024-06-14 12:34:20");++ const wrapper = container.querySelector(".cell-styles");+ expect(wrapper).not.toBeNull();+ wrapper?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ expect(selectCell).toHaveBeenCalledTimes(1);+ });++ it("should render the column format for Date instances", () => {+ const mockColumn = {+ ...createMockColumn(),+ getColumnFormatting: () => "Date",+ applyColumnFormatting: () => "FORMATTED",+ } as unknown as Column<unknown>;+ const value = new Date("2024-06-14T12:34:20Z");++ const result = renderCellValue({+ column: mockColumn,+ renderValue: () => value,+ getValue: () => value,+ selectCell: undefined,+ cellStyles: "",+ });+ const { container } = render(+ <I18nProvider locale="en-US">+ <TooltipProvider>{result}</TooltipProvider>+ </I18nProvider>,+ );+ expect(container.textContent).toContain("FORMATTED");+ });++ it("should keep the raw string when no column format is set", () => {+ const mockColumn = createMockColumn();++ const result = renderCellValue({+ column: mockColumn,+ renderValue: () => "2024-06-14",+ getValue: () => "2024-06-14",+ selectCell: undefined,+ cellStyles: "",+ });+ const { container } = render(+ <I18nProvider locale="en-US">+ <TooltipProvider>{result}</TooltipProvider>+ </I18nProvider>,+ );+ expect(container.textContent).toContain("2024-06-14");+ });});test("column_widths sets fixed size and meta.width", () => {diff --git a/frontend/src/components/data-table/column-formatting/feature.ts b/frontend/src/components/data-table/column-formatting/feature.tsindex e647cff3f0..ba4123bac9 100644--- a/frontend/src/components/data-table/column-formatting/feature.ts+++ b/frontend/src/components/data-table/column-formatting/feature.ts@@ -97,6 +97,7 @@ export const getFormatters = memoizeLastValue((locale: string) => {const dateFormatter = new Intl.DateTimeFormat(locale, {dateStyle: "short", // 3/4/2024+ timeZone: "UTC",});const dateTimeFormatter = new Intl.DateTimeFormat(locale, {@@ -123,6 +124,24 @@ export const getFormatters = memoizeLastValue((locale: string) => {};});+const TIMEZONE_SUFFIX = /(?:Z|[+-]\d{2}:?\d{2})$/i;++/**+ * The date formatters render in UTC. A naive datetime string carries no+ * offset, and `new Date` would read it as local time, so pin it to UTC+ * to keep the wall-clock fields the backend sent.+ */+function parseDateAsUTC(value: unknown): Date {+ if (typeof value !== "string") {+ return new Date(value as number | Date);+ }+ const trimmed = value.trim();+ if (TIMEZONE_SUFFIX.test(trimmed) || !trimmed.includes(":")) {+ return new Date(trimmed);+ }+ return new Date(`${trimmed.replace(" ", "T")}Z`);+}+// Apply formatting to a value given a format and data typeexport const applyFormat = (value: unknown,@@ -152,7 +171,7 @@ export const applyFormat = (return value;case "datetime":case "date": {- const date = new Date(value as string);+ const date = parseDateAsUTC(value);switch (format) {case "Date":return dateFormatter.format(date);diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex fa9105669c..ff2e8b4fe2 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -6,14 +6,14 @@ import { Popover as PopoverPrimitive } from "radix-ui";const PopoverClose = PopoverPrimitive.Close;import type { Column, ColumnDef } from "@tanstack/react-table";-import { formatDate, isValid } from "date-fns";+import { isValid } from "date-fns";import { useRef } from "react";import { useLocale, useNumberFormatter } from "react-aria";import { WithLocale } from "@/core/i18n/with-locale";import type { DataType } from "@/core/kernel/messages";import type { CalculateTopKRows } from "@/plugins/impl/DataTablePlugin";import { cn } from "@/utils/cn";-import { type DateFormat, exactDateTime, getDateFormat } from "@/utils/dates";+import { exactDateTime } from "@/utils/dates";import { Events } from "@/utils/events";import { Logger } from "@/utils/Logger";import { Maps } from "@/utils/maps";@@ -583,21 +583,19 @@ function renderDate({value,dataType,dtype,- format,+ displayValue,locale,}: {value: Date;dataType?: DataType;dtype?: string;- format?: DateFormat | null;+ displayValue?: string;locale: string;}): React.ReactNode {const type = dataType === "date" ? "date" : "datetime";const timezone = extractTimezone(dtype);- const exactValue = format- ? formatDate(value, format)- : exactDateTime(value, timezone, locale);+ const exactValue = displayValue ?? exactDateTime(value, timezone, locale);return (<DatePopover date={value} type={type}>@@ -640,7 +638,8 @@ export function renderCellValue<TData, TValue>({if (dataType === "datetime" && typeof value === "string") {try {- if (!isValid(value)) {+ const date = new Date(value);+ if (!format || !isValid(date)) {return (<div onClick={selectCell} className={cellStyles}>{value}@@ -648,14 +647,15 @@ export function renderCellValue<TData, TValue>({);}- const date = new Date(value);- const format = getDateFormat(value);+ const displayValue = String(column.applyColumnFormatting(value));return (- <WithLocale>- {(locale) =>- renderDate({ value: date, dataType, dtype, format, locale })- }- </WithLocale>+ <div onClick={selectCell} className={cellStyles}>+ <WithLocale>+ {(locale) =>+ renderDate({ value: date, dataType, dtype, displayValue, locale })+ }+ </WithLocale>+ </div>);} catch (error) {Logger.error("Error parsing datetime, fallback to string", error);@@ -672,10 +672,17 @@ export function renderCellValue<TData, TValue>({}// e.g. 2010-10-07 17:15:00+ const displayValue = format+ ? String(column.applyColumnFormatting(value))+ : undefined;return (- <WithLocale>- {(locale) => renderDate({ value, dataType, dtype, locale })}- </WithLocale>+ <div onClick={selectCell} className={cellStyles}>+ <WithLocale>+ {(locale) =>+ renderDate({ value, dataType, dtype, displayValue, locale })+ }+ </WithLocale>+ </div>);}