The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
chore: replace moment-timezone with dayjs for main app (#63334)
Uladzimir Havenchyk5b0164a622b2
diff --git a/frontend/src/metabase-types/guards/settings.ts b/frontend/src/metabase-types/guards/settings.tsindex 96bfb13f271..7518d4d7327 100644--- a/frontend/src/metabase-types/guards/settings.ts+++ b/frontend/src/metabase-types/guards/settings.ts@@ -1,5 +1,23 @@-import { type EngineKey, engineKeys } from "metabase-types/api";+import {+ type EngineKey,+ type ScheduleDayType,+ engineKeys,+} from "metabase-types/api";++export const SCHEDULE_DAY: ScheduleDayType[] = [+ "sun",+ "mon",+ "tue",+ "wed",+ "thu",+ "fri",+ "sat",+];export function isEngineKey(value: string | undefined): value is EngineKey {return engineKeys.includes(value as EngineKey);}++export function isScheduleDay(value: string): value is ScheduleDayType {+ return SCHEDULE_DAY.includes(value as ScheduleDayType);+}diff --git a/frontend/src/metabase/forms/components/FormDateInput/FormDateInput.tsx b/frontend/src/metabase/forms/components/FormDateInput/FormDateInput.tsxindex d4d362d84a7..7c122c24438 100644--- a/frontend/src/metabase/forms/components/FormDateInput/FormDateInput.tsx+++ b/frontend/src/metabase/forms/components/FormDateInput/FormDateInput.tsx@@ -39,7 +39,7 @@ export const FormDateInput = forwardRef(function FormDateInput(const handleChange = useCallback((date: DateValue | undefined) => {if (date) {- setValue(dayjs(date).toISOString());+ setValue(dayjs(date).format("YYYY-MM-DD"));} else {setValue(nullable ? null : undefined);}diff --git a/frontend/src/metabase/lib/dayjs-parse-zone-plugin.js b/frontend/src/metabase/lib/dayjs-parse-zone-plugin.jsindex 62c616068fb..26a47756ec2 100644--- a/frontend/src/metabase/lib/dayjs-parse-zone-plugin.js+++ b/frontend/src/metabase/lib/dayjs-parse-zone-plugin.js@@ -1,7 +1,8 @@// This is the copy of https://github.com/iamkun/dayjs/pull/2060 which implements parseZone// which we rely on when using momentjs so we need this plugin to be able to migrate from momentjs// @authors: LucaColonnello and all contributors from https://github.com/iamkun/dayjs/issues/651#issuecomment-763033265-const REGEX_TIMEZONE_OFFSET_FORMAT = /^(.*)([+-])(\d{2}):(\d{2})|(Z)$/;+// The colon is made optional with ':?' to support both '+0100' and '+01:00' timezone formats.+const REGEX_TIMEZONE_OFFSET_FORMAT = /^(.*)([+-])(\d{2}):?(\d{2})|(Z)$/;const parseOffset = (dateString) =>dateString.match(REGEX_TIMEZONE_OFFSET_FORMAT);@@ -47,8 +48,19 @@ const pluginFunc = (option, dayjsClass, dayjsFactory) => {const [, dateTime] = match;const offset = formatOffset(match);+ // Fix millisecond parsing for timestamps with fewer than 3 decimal places+ // related issue https://github.com/iamkun/dayjs/issues/2459+ let adjustedDateTime = dateTime;+ const millisecondsMatch = dateTime.match(/(\.\d{1,2})$/);+ if (millisecondsMatch) {+ const [, ms] = millisecondsMatch;+ // Pad milliseconds to 3 digits (e.g., .01 -> .010, .1 -> .100)+ const paddedMs = ms.padEnd(4, "0"); // .xxx format+ adjustedDateTime = dateTime.replace(/\.\d{1,2}$/, paddedMs);+ }+return dayjsFactory(- dateTime,+ adjustedDateTime,{$offset: offset,...format,diff --git a/frontend/src/metabase/lib/dayjs-parse-zone-plugin.unit.spec.js b/frontend/src/metabase/lib/dayjs-parse-zone-plugin.unit.spec.jsnew file mode 100644index 00000000000..002d17a1c4b--- /dev/null+++ b/frontend/src/metabase/lib/dayjs-parse-zone-plugin.unit.spec.js@@ -0,0 +1,58 @@+import dayjs from "dayjs";++describe("parse zone", () => {+ it("holds the original offset instead of converting to local", () => {+ const dParseZone = dayjs.parseZone("2013-01-01T00:00:00-13:00");+ const dWithoutParseZone = dayjs.utc("2013-01-01T00:00:00-13:00");++ expect(dParseZone.format("Z")).toEqual("-13:00");+ expect(dWithoutParseZone.format("Z")).toEqual("+00:00");+ });++ it("handles positive and negative timezone", () => {+ const dNegative = dayjs.parseZone("2013-01-01T00:00:00-13:00");+ const dPositive = dayjs.parseZone("2013-01-01T00:00:00+13:00");++ expect(dPositive.format("YYYY-MM-DD HH:mm:ss Z")).toEqual(+ "2013-01-01 00:00:00 +13:00",+ );+ expect(dNegative.format("YYYY-MM-DD HH:mm:ss Z")).toEqual(+ "2013-01-01 00:00:00 -13:00",+ );+ });++ it("works with custom format plugin", () => {+ const d = dayjs.parseZone(+ "2013 01 01 00:00:00 -13:00",+ "YYYY MM DD HH:mm:ss",+ );+ expect(d.format("YYYY-MM-DD HH:mm:ss")).toEqual("2013-01-01 00:00:00");+ });++ it("uses default constructor when no date string is provided", () => {+ const d = dayjs.parseZone(new Date(2013, 0, 1, 0, 0, 0));+ expect(d.format("YYYY-MM-DD HH:mm:ss")).toEqual("2013-01-01 00:00:00");+ });++ it("keeps the time and change the zone to 0 when no timezone is provided", () => {+ const d = dayjs.parseZone("2013-01-01T00:00:00");+ expect(d.format("YYYY-MM-DD HH:mm:ss")).toEqual("2013-01-01 00:00:00");+ });++ it("handles UTC format", () => {+ const d = dayjs.parseZone("2013-01-01T00:00:00Z");+ expect(d.format("YYYY-MM-DD HH:mm:ss")).toEqual(+ dayjs.utc("2013-01-01T00:00:00").format("YYYY-MM-DD HH:mm:ss"),+ );+ });++ // related issue https://github.com/iamkun/dayjs/issues/2459+ it.failing("add pads to the not complete date", () => {+ const d = dayjs.parseZone("2025-03-11T20:45:17.01");+ expect(d.format("MMMM DD, YYYY, h:mm:ss.SSS A")).toEqual(+ dayjs("March 11, 2025, 8:45:17.010 PM").format(+ "MMMM DD, YYYY, h:mm:ss.SSS A",+ ),+ );+ });+});diff --git a/frontend/src/metabase/lib/dayjs.ts b/frontend/src/metabase/lib/dayjs.tsindex e8fac6f9a56..7f382c2d4f2 100644--- a/frontend/src/metabase/lib/dayjs.ts+++ b/frontend/src/metabase/lib/dayjs.ts@@ -3,9 +3,11 @@ import advancedFormat from "dayjs/plugin/advancedFormat";import customParseFormat from "dayjs/plugin/customParseFormat";import dayOfYear from "dayjs/plugin/dayOfYear";import duration from "dayjs/plugin/duration";+import isBetween from "dayjs/plugin/isBetween";import isoWeekPlugin from "dayjs/plugin/isoWeek";import localeData from "dayjs/plugin/localeData";import localizedFormat from "dayjs/plugin/localizedFormat";+import preParsePostFormat from "dayjs/plugin/preParsePostFormat";import quarterOfYear from "dayjs/plugin/quarterOfYear";import relativeTime from "dayjs/plugin/relativeTime";import timezone from "dayjs/plugin/timezone";@@ -31,3 +33,5 @@ dayjs.extend(weekday);dayjs.extend(weekOfYear);dayjs.extend(parseZone);dayjs.extend(duration);+dayjs.extend(isBetween);+dayjs.extend(preParsePostFormat);diff --git a/frontend/src/metabase/lib/formatting/date.tsx b/frontend/src/metabase/lib/formatting/date.tsxindex ff907c3a32f..2dc456fb93a 100644--- a/frontend/src/metabase/lib/formatting/date.tsx+++ b/frontend/src/metabase/lib/formatting/date.tsx@@ -1,12 +1,13 @@import cx from "classnames";-import type { Moment } from "moment-timezone"; // eslint-disable-line no-restricted-imports -- deprecated usage-import moment from "moment-timezone"; // eslint-disable-line no-restricted-imports -- deprecated usage+import dayjs, { type Dayjs, type OpUnitType, type QUnitType } from "dayjs";import { t } from "ttag";import CS from "metabase/css/core/index.css";-import { parseTimestamp } from "metabase/lib/time";import { isDateWithoutTime } from "metabase-lib/v1/types/utils/isa";import type { DatetimeUnit } from "metabase-types/api/query";+import { SCHEDULE_DAY, isScheduleDay } from "metabase-types/guards/settings";++import { parseTimestamp } from "../time-dayjs";import {DEFAULT_DATE_STYLE,@@ -61,10 +62,10 @@ const DATE_STYLE_TO_FORMAT: DATE_STYLE_TO_FORMAT_TYPE = {const DATE_RANGE_MONTH_PLACEHOLDER = "<MONTH>";-type DateVal = string | number | Moment;+type DateVal = string | number | Dayjs;interface DateRangeFormatSpec {- same: null | moment.unitOfTime.StartOf;+ same: null | OpUnitType | QUnitType;format: [string] | [string, string];removedYearFormat?: [string] | [string, string];removedDayFormat?: [string] | [string, string];@@ -803,7 +804,7 @@ export function normalizeDateTimeRangeWithUnit(values: [DateVal] | [DateVal, DateVal],unit: DatetimeUnit,options: OptionsType = {},-) {+): [Dayjs, Dayjs, number] | [Dayjs, Dayjs] {const [a, b] = [values[0], values[1] ?? values[0]].map((d) =>parseTimestamp(d, unit, options.local),);@@ -812,15 +813,16 @@ export function normalizeDateTimeRangeWithUnit(}// week-of-year → week, minute-of-hour → minute, etc- const momentUnit = unit.split("-")[0];+ const dayjsUnit = unit.split("-")[0] as OpUnitType;// The client's unit boundaries might not line up with the data returned from the server.// We shift the range so that the start lines up with the value.- const start = a.clone().startOf(momentUnit);- const end = b.clone().endOf(momentUnit);+ const start = a.clone().startOf(dayjsUnit);+ const end = b.clone().endOf(dayjsUnit);const shift = a.diff(start, "days");- [start, end].forEach((d) => d.add(shift, "days"));- return [start, end, shift];+ const shiftedStart = start.add(shift, "days");+ const shiftedEnd = end.add(shift, "days");+ return [shiftedStart, shiftedEnd, shift];}/** This formats a time with unit as a date range */@@ -829,14 +831,13 @@ export function formatDateTimeRangeWithUnit(unit: DatetimeUnit,options: OptionsType = {},) {- const [start, end, shift] = normalizeDateTimeRangeWithUnit(- values,- unit,- options,- );- if (shift === undefined) {+ const result = normalizeDateTimeRangeWithUnit(values, unit, options);+ if (result.length === 2) {+ const [start, _end] = result;return String(start);- } else if (!start.isValid() || !end.isValid()) {+ }+ const [start, end, _shift] = result;+ if (!start.isValid() || !end.isValid()) {// TODO: when is this used?return formatWeek(start, options);}@@ -854,11 +855,28 @@ export function formatDateTimeRangeWithUnit(return String(start);}- const formatDate = (date: Moment, formatStr: string) => {+ const formatDate = (date: Dayjs, formatStr: string) => {// month format is configurable, so we need to insert it after lookup- return date.format(- formatStr.replace(DATE_RANGE_MONTH_PLACEHOLDER, monthFormat),+ const processedFormat = formatStr.replace(+ DATE_RANGE_MONTH_PLACEHOLDER,+ monthFormat,);++ // Fix for day-of-year formatting: replace DDD and DDDo with custom formatting+ // because dayjs DDD format token doesn't work like moment's DDD+ if (processedFormat.includes("DDDo")) {+ const dayOfYear = date.dayOfYear();+ const ordinal = dayjs().localeData().ordinal(dayOfYear);+ const formattedDate = processedFormat+ // Replace DDDo token+ .replace(/DDDo/g, ordinal)+ // Remove brackets from literal text since we're not using dayjs formatting+ .replace(/\[([^\]]+)\]/g, "$1");++ return formattedDate;+ }++ return date.format(processedFormat);};if (!condensed) {@@ -933,10 +951,10 @@ export function formatDateTimeRangeWithUnit(}interface formatDateStringParameters {- start: Moment;+ start: Dayjs;startFormat: string;- formatDate: (date: Moment, format: string) => string;- end?: Moment;+ formatDate: (date: Dayjs, format: string) => string;+ end?: Dayjs;endFormat?: string | undefined;dashPad?: string;}@@ -979,7 +997,7 @@ export function formatRange(}}-function formatWeek(m: Moment, options: OptionsType = {}) {+function formatWeek(m: Dayjs, options: OptionsType = {}) {return formatMajorMinor(m.format("wo"), m.format("gggg"), options);}@@ -1018,12 +1036,12 @@ function replaceDateFormatNames(format: string, options: OptionsType) {}export function formatDateTimeWithFormats(- value: number | string | Date | Moment,+ value: number | string | Date | Dayjs,dateFormat: string,timeFormat: string | null,options: OptionsType,) {- const m = moment.isMoment(value)+ const m = dayjs.isDayjs(value)? value: parseTimestamp(value,@@ -1049,16 +1067,35 @@ export function formatDateTimeWithFormats(}export function formatDateTimeWithUnit(- value: number | string | Date | Moment,+ value: number | string | Date | Dayjs,unit: DatetimeUnit,options: OptionsType = {},) {- if (options.isExclude && unit === "hour-of-day") {- return moment.utc(value).format("h A");- } else if (options.isExclude && unit === "day-of-week") {- const date = moment.utc(value);+ if (options.isExclude) {+ if (unit === "hour-of-day") {+ return dayjs.utc(value).format("h A");+ }++ if (unit === "day-of-week") {+ const date = dayjs.utc(value);++ if (date.isValid()) {+ return date.format("dddd");+ }+ }+ }++ if (+ unit === "day-of-week" &&+ typeof value === "string" &&+ isScheduleDay(value)+ ) {+ const dayIndex = SCHEDULE_DAY.indexOf(value);+ const date = dayjs().day(dayIndex);+if (date.isValid()) {- return date.format("dddd");+ const dayFormat = getDayFormat(options);+ return date.format(dayFormat);}}@@ -1067,6 +1104,15 @@ export function formatDateTimeWithUnit(return String(value);}+ // dayjs can't format DDD to day of year, handle manually+ if (unit === "day-of-year") {+ return m.dayOfYear();+ }++ if (unit === "week-of-year") {+ return dayjs().localeData().ordinal(m.isoWeek()).slice(1, -1);+ }+// expand "week" into a range in specific contextsif (unit === "week") {if (@@ -1108,7 +1154,7 @@ export function formatDateTimeWithUnit(return formatDateTimeWithFormats(m, dateFormat, timeFormat, options);}-const EXAMPLE_DATE = moment("2018-01-31 17:24");+const EXAMPLE_DATE = dayjs("2018-01-31 17:24");export function getDateStyleOptionsForUnit(unit: DatetimeUnit,diff --git a/frontend/src/metabase/lib/formatting/link.ts b/frontend/src/metabase/lib/formatting/link.tsindex 3c1b4db8877..4fcaeacae4e 100644--- a/frontend/src/metabase/lib/formatting/link.ts+++ b/frontend/src/metabase/lib/formatting/link.ts@@ -67,7 +67,10 @@ export function renderLinkURLForClick() => {const valueForLinkTemplate = formatValueForLinkTemplate(value, column);- if ([null, NULL_DISPLAY_VALUE].includes(valueForLinkTemplate)) {+ if (+ valueForLinkTemplate == null ||+ valueForLinkTemplate === NULL_DISPLAY_VALUE+ ) {return "";}@@ -85,12 +88,16 @@ export function renderLinkURLForClick(// Also, this only makes sense when such parameters are at the beginning of the link template.const isColumnValue = column != null;const isStart = offset === 0;+ const isStringValue = typeof valueForLinkTemplate === "string";const shouldSkipEncoding =- isColumnValue && isStart && isSafeUrl(valueForLinkTemplate);+ isColumnValue &&+ isStart &&+ isStringValue &&+ isSafeUrl(valueForLinkTemplate);return shouldSkipEncoding? valueForLinkTemplate- : encodeURIComponent(valueForLinkTemplate);+ : encodeURIComponent(String(valueForLinkTemplate));},);}diff --git a/frontend/src/metabase/lib/formatting/time.ts b/frontend/src/metabase/lib/formatting/time.tsindex 652e98a0045..6ae47da613e 100644--- a/frontend/src/metabase/lib/formatting/time.ts+++ b/frontend/src/metabase/lib/formatting/time.ts@@ -1,9 +1,8 @@-import type { Moment } from "moment-timezone"; // eslint-disable-line no-restricted-imports -- deprecated usage+import type { Dayjs } from "dayjs";import { msgid, ngettext } from "ttag";import type { TimeOnlyOptions } from "metabase/lib/formatting/types";-import { parseTime } from "metabase/lib/time";-import { parseTimestamp } from "metabase/lib/time-dayjs";+import { parseTime, parseTimestamp } from "metabase/lib/time-dayjs";import type { DatetimeUnit } from "metabase-types/api/query";import {@@ -65,7 +64,7 @@ export function formatTimeWithUnit(}export function formatTime(- time: Moment,+ time: Dayjs,unit: DatetimeUnit = "default",options: TimeOnlyOptions = {},) {diff --git a/frontend/src/metabase/lib/formatting/value.tsx b/frontend/src/metabase/lib/formatting/value.tsxindex 0787bdebf6b..9c12850d4d5 100644--- a/frontend/src/metabase/lib/formatting/value.tsx+++ b/frontend/src/metabase/lib/formatting/value.tsx@@ -1,6 +1,5 @@import cx from "classnames";-import dayjs from "dayjs";-import type { Moment } from "moment-timezone"; // eslint-disable-line no-restricted-imports -- deprecated usage+import dayjs, { type Dayjs } from "dayjs";import Mustache from "mustache";import ReactMarkdown from "react-markdown";@@ -185,7 +184,7 @@ export function formatValueRaw(} else if (isEmail(column)) {return formatEmail(value as string, options);} else if (isTime(column)) {- return formatTime(value as Moment, column.unit, options);+ return formatTime(value as Dayjs, column.unit, options);} else if (column && column.unit != null) {return formatDateTimeWithUnit(value as string | number,diff --git a/frontend/src/metabase/lib/i18n.js b/frontend/src/metabase/lib/i18n.jsindex 62471a53e7a..e361b93ba1f 100644--- a/frontend/src/metabase/lib/i18n.js+++ b/frontend/src/metabase/lib/i18n.js@@ -71,6 +71,7 @@ export function setLocalization(translationsObject) {if (ARABIC_LOCALES.includes(language)) {preverseLatinNumbersInMomentLocale(language);+ preverseLatinNumbersInDayjsLocale(language);}}@@ -101,6 +102,19 @@ function preverseLatinNumbersInMomentLocale(locale) {});}+// a copy of moment function+function preverseLatinNumbersInDayjsLocale(locale) {+ dayjs.updateLocale(locale, {+ postformat(string) {+ return string.replace(/,/g, "،");+ },+ meridiem: (hour) => {+ // https://github.com/iamkun/dayjs/pull/2717#issuecomment-2868626450+ return hour < 12 ? "ص" : "م";+ },+ });+}+function updateDayjsLocale(language) {const locale = getLocale(language);diff --git a/frontend/src/metabase/lib/i18n.unit.spec.ts b/frontend/src/metabase/lib/i18n.unit.spec.tsindex 0a4a5f95768..241247aa4dc 100644--- a/frontend/src/metabase/lib/i18n.unit.spec.ts+++ b/frontend/src/metabase/lib/i18n.unit.spec.ts@@ -1,4 +1,4 @@-import moment from "moment-timezone"; // eslint-disable-line no-restricted-imports -- deprecated usage+import dayjs from "dayjs";import { setLocalization } from "./i18n";@@ -12,22 +12,24 @@ function setup(language: string) {describe("setLocalization", () => {it("should preserve latin numbers when formatting dates in 'ar' locale", () => {setup("ar");- const m = moment.utc("2023-10-12T21:07:33.476Z");+ const date = dayjs.utc("2023-10-12T21:07:33.476Z");- expect(m.format("MMMM D, YYYY, h:mm A")).toBe("أكتوبر 12، 2023، 9:07 م");+ expect(date.format("MMMM D, YYYY, h:mm A")).toBe("أكتوبر 12، 2023، 9:07 م");});it("should preserve latin numbers when formatting dates in 'ar-sa' locale", () => {setup("ar-sa");- const m = moment.utc("2023-10-12T21:07:33.476Z");+ const date = dayjs.utc("2023-10-12T21:07:33.476Z");- expect(m.format("MMMM D, YYYY, h:mm A")).toBe("أكتوبر 12، 2023، 9:07 م");+ expect(date.format("MMMM D, YYYY, h:mm A")).toBe("أكتوبر 12، 2023، 9:07 م");});it("should preserve latin numbers in the 'en' locale", () => {setup("en");- const m = moment.utc("2023-10-12T21:07:33.476Z");+ const date = dayjs.utc("2023-10-12T21:07:33.476Z");- expect(m.format("MMMM D, YYYY, h:mm A")).toBe("October 12, 2023, 9:07 PM");+ expect(date.format("MMMM D, YYYY, h:mm A")).toBe(+ "October 12, 2023, 9:07 PM",+ );});});diff --git a/frontend/src/metabase/lib/time-dayjs.ts b/frontend/src/metabase/lib/time-dayjs.tsindex a92e5423620..70088e4a8de 100644--- a/frontend/src/metabase/lib/time-dayjs.ts+++ b/frontend/src/metabase/lib/time-dayjs.ts@@ -29,8 +29,8 @@ export function getDaylightSavingsChangeTolerance(unit: string) {const TEXT_UNIT_FORMATS = {"day-of-week": (value: string) => {- const day = dayjs.tz(value, "ddd").startOf("day");- return day.isValid() ? day : dayjs.tz(value).startOf("day");+ const day = dayjs(value, "ddd").startOf("day");+ return day.isValid() ? day : dayjs(value).startOf("day");},};@@ -79,7 +79,15 @@ export function parseTimestamp(} else if (unit && unit in NUMERIC_UNIT_FORMATS && typeof value == "number") {result = NUMERIC_UNIT_FORMATS[unit](value);} else if (typeof value === "number") {- result = dayjs.utc(value.toString());+ // When a unit is provided but not in NUMERIC_UNIT_FORMATS, small numbers+ // don't make sense as timestamps. For example, parseTimestamp(1, "month")+ // should not interpret 1 as "1 millisecond since epoch".+ // Use strict parsing for small numbers to return invalid dates.+ if (unit && value < 1000) {+ result = dayjs.utc(value, "", true);+ } else {+ result = dayjs.utc(value.toString());+ }} else {result = dayjs.utc(value);}@@ -102,3 +110,24 @@ export function formatFrame(frame: "first" | "last" | "mid") {return frame;}}++export function timezoneToUTCOffset(timezone: string) {+ // Use a fixed date in winter (non-DST) to get consistent offsets+ return dayjs("2024-07-01").tz(timezone).format("Z");+}++export function parseTime(value: Dayjs | string) {+ if (dayjs.isDayjs(value)) {+ return value;+ } else if (typeof value === "string") {+ // removing the timezone part if it exists, so we can parse the time correctly+ return dayjs(value.split(/[+-]/)[0], [+ "HH:mm:ss.SSSZ",+ "HH:mm:ss.SSS",+ "HH:mm:ss",+ "HH:mm",+ ]);+ }++ return dayjs.utc(value);+}diff --git a/frontend/src/metabase/lib/time-dayjs.unit.spec.ts b/frontend/src/metabase/lib/time-dayjs.unit.spec.tsindex 95281425f4e..cb08cc84c46 100644--- a/frontend/src/metabase/lib/time-dayjs.unit.spec.ts+++ b/frontend/src/metabase/lib/time-dayjs.unit.spec.ts@@ -1,20 +1,74 @@import dayjs from "dayjs";-import { parseTimestamp } from "metabase/lib/time-dayjs";+import {+ parseTime,+ parseTimestamp,+ timezoneToUTCOffset,+} from "metabase/lib/time-dayjs";-describe("parseTimestamp", () => {- afterEach(() => {- dayjs.updateLocale(dayjs.locale(), { weekStart: 0 });- });+describe("time-dayjs", () => {+ describe("parseTimestamp", () => {+ afterEach(() => {+ dayjs.updateLocale(dayjs.locale(), { weekStart: 0 });+ });++ it("should parse week of year correctly", () => {+ const daysOfWeek = [0, 1, 2, 3, 4, 5, 6];+ daysOfWeek.forEach((dayOfWeek) => {+ dayjs.updateLocale(dayjs.locale(), { weekStart: dayOfWeek });+ expect(parseTimestamp(1, "week-of-year").isoWeek()).toBe(1);+ expect(parseTimestamp(2, "week-of-year").isoWeek()).toBe(2);+ expect(parseTimestamp(52, "week-of-year").isoWeek()).toBe(52);+ expect(parseTimestamp(53, "week-of-year").isoWeek()).toBe(53);+ });+ });++ it("should not parse small numbers as timestamps when non-timestamp unit is provided", () => {+ // When unit="month", small numbers should return an invalid date+ // rather than being interpreted as milliseconds since epoch+ const result = parseTimestamp(1, "month");- it("should parse week of year correctly", () => {- const daysOfWeek = [0, 1, 2, 3, 4, 5, 6];- daysOfWeek.forEach((dayOfWeek) => {- dayjs.updateLocale(dayjs.locale(), { weekStart: dayOfWeek });- expect(parseTimestamp(1, "week-of-year").isoWeek()).toBe(1);- expect(parseTimestamp(2, "week-of-year").isoWeek()).toBe(2);- expect(parseTimestamp(52, "week-of-year").isoWeek()).toBe(52);- expect(parseTimestamp(53, "week-of-year").isoWeek()).toBe(53);+ // Small numbers with units like "month", "quarter", "year" don't make sense+ // as timestamps, so parseTimestamp should return an invalid date+ expect(result.isValid()).toBe(false);});});++ describe("timezoneToUTCOffset", () => {+ it.each([+ ["UTC", "+00:00"],+ ["America/New_York", "-04:00"],+ ["America/Los_Angeles", "-07:00"],+ ["Europe/London", "+01:00"],+ ["Asia/Tokyo", "+09:00"],+ ["Pacific/Auckland", "+12:00"],+ ])(+ "should return the correct UTC offset for %s",+ (timezone, expectedOffset) => {+ expect(timezoneToUTCOffset(timezone)).toBe(expectedOffset);+ },+ );+ });++ describe("parseTime", () => {+ const PARSE_TIME_TESTS = [+ ["01:02:03.456+07:00", "1:02 AM"],+ ["01:02", "1:02 AM"],+ ["22:29:59.26816+01:00", "10:29 PM"],+ ["22:29:59.412459+01:00", "10:29 PM"],+ ["19:14:42.926221+01:00", "7:14 PM"],+ ["19:14:42.13202+01:00", "7:14 PM"],+ ["13:38:58.987352+01:00", "1:38 PM"],+ ["13:38:58.001001+01:00", "1:38 PM"],+ ["17:01:23+01:00", "5:01 PM"],+ ];++ test.each(PARSE_TIME_TESTS)(+ `parseTime(%p) to be %p`,+ (value, resultStr) => {+ const result = parseTime(value);+ expect(result.format("h:mm A")).toBe(resultStr);+ },+ );+ });});diff --git a/frontend/src/metabase/lib/time.ts b/frontend/src/metabase/lib/time.tsindex 5c7551dbb80..b4d8ec005f0 100644--- a/frontend/src/metabase/lib/time.ts+++ b/frontend/src/metabase/lib/time.ts@@ -6,6 +6,10 @@ import type { DatetimeUnit } from "metabase-types/api/query";addAbbreviatedLocale();+// NOTE for developer:+// this file is deprecated, do not modify it unless it is really necessary+// use ./time-dayjs.ts instead+const TIME_FORMAT_24_HOUR = "HH:mm";const TEXT_UNIT_FORMATS = {@@ -74,7 +78,7 @@ function addAbbreviatedLocale() {moment.locale(initialLocale);}-export function getTimeStyleFromSettings() {+function getTimeStyleFromSettings() {const customFormattingSettings = MetabaseSettings.get("custom-formatting");return customFormattingSettings?.["type/Temporal"]?.time_style;}diff --git a/frontend/src/metabase/query_builder/selectors.js b/frontend/src/metabase/query_builder/selectors.jsindex 1f8877e150b..570c8d120c4 100644--- a/frontend/src/metabase/query_builder/selectors.js+++ b/frontend/src/metabase/query_builder/selectors.js@@ -8,7 +8,7 @@ import { LOAD_COMPLETE_FAVICON } from "metabase/common/hooks/constants";import Databases from "metabase/entities/databases";import { cleanIndexFlags } from "metabase/entities/model-indexes/actions";import Timelines from "metabase/entities/timelines";-import { parseTimestamp } from "metabase/lib/time";+import { parseTimestamp } from "metabase/lib/time-dayjs";import { getSortedTimelines } from "metabase/lib/timelines";import { isNotNull } from "metabase/lib/types";import {diff --git a/frontend/test/metabase/lib/formatting.unit.spec.js b/frontend/test/metabase/lib/formatting.unit.spec.jsindex 598afceccac..fc10db1dd86 100644--- a/frontend/test/metabase/lib/formatting.unit.spec.js+++ b/frontend/test/metabase/lib/formatting.unit.spec.js@@ -1,4 +1,4 @@-import moment from "moment-timezone"; // eslint-disable-line no-restricted-imports -- deprecated usage+import dayjs from "dayjs";import { isElementOfType } from "react-dom/test-utils";import { mockSettings } from "__support__/settings";@@ -660,18 +660,15 @@ describe("formatting", () => {});it("should always format week ranges according to returned data", () => {- try {- // globally set locale to es- moment.locale("es");- expect(- formatDateTimeWithUnit("2019-07-07T00:00:00.000Z", "week", {- type: "cell",- }),- ).toEqual("julio 7, 2019 – julio 13, 2019");- } finally {- // globally reset locale- moment.locale("en");- }+ setSpanishLocale();++ expect(+ formatDateTimeWithUnit("2019-07-07T00:00:00.000Z", "week", {+ type: "cell",+ }),+ ).toEqual("julio 7, 2019 – julio 13, 2019");++ resetLocale();});it("should format days of week with default options", () => {@@ -732,9 +729,66 @@ describe("formatting", () => {},);- it.each([1, 2, 52, 53])("should format week numbers correctly", (value) => {- const text = formatDateTimeWithUnit(value, "week-of-year");- expect(text).toMatch(new RegExp(`${value}[a-z]+`));+ describe("day-of-year formatting", () => {+ it("should format day-of-year as plain number", () => {+ expect(formatDateTimeWithUnit(1, "day-of-year")).toEqual(1);+ expect(formatDateTimeWithUnit(100, "day-of-year")).toEqual(100);+ expect(formatDateTimeWithUnit(365, "day-of-year")).toEqual(365);+ });++ it("should format day-of-year from date strings", () => {+ // January 1st = day 1+ expect(formatDateTimeWithUnit("2023-01-01", "day-of-year")).toEqual(1);+ // February 1st = day 32 (31 days in January + 1)+ expect(formatDateTimeWithUnit("2023-02-01", "day-of-year")).toEqual(32);+ // December 31st = day 365 (non-leap year)+ expect(formatDateTimeWithUnit("2023-12-31", "day-of-year")).toEqual(+ 365,+ );+ });++ it("should handle leap year correctly", () => {+ // December 31st in a leap year = day 366+ expect(formatDateTimeWithUnit("2020-12-31", "day-of-year")).toEqual(+ 366,+ );+ // February 29th in a leap year = day 60+ expect(formatDateTimeWithUnit("2020-02-29", "day-of-year")).toEqual(60);+ });+ });++ describe("week-of-year formatting", () => {+ it("should format week numbers with ordinal suffixes", () => {+ expect(formatDateTimeWithUnit(1, "week-of-year")).toEqual("1st");+ expect(formatDateTimeWithUnit(2, "week-of-year")).toEqual("2nd");+ expect(formatDateTimeWithUnit(3, "week-of-year")).toEqual("3rd");+ expect(formatDateTimeWithUnit(4, "week-of-year")).toEqual("4th");+ expect(formatDateTimeWithUnit(21, "week-of-year")).toEqual("21st");+ expect(formatDateTimeWithUnit(22, "week-of-year")).toEqual("22nd");+ expect(formatDateTimeWithUnit(23, "week-of-year")).toEqual("23rd");+ expect(formatDateTimeWithUnit(24, "week-of-year")).toEqual("24th");+ expect(formatDateTimeWithUnit(53, "week-of-year")).toEqual("53rd");+ });++ it("should handle edge cases for ordinal suffixes", () => {+ expect(formatDateTimeWithUnit(11, "week-of-year")).toEqual("11th");+ expect(formatDateTimeWithUnit(12, "week-of-year")).toEqual("12th");+ expect(formatDateTimeWithUnit(13, "week-of-year")).toEqual("13th");+ });++ it("should format week-of-year from date strings", () => {+ // January 1st, 2023 (Sunday) is in week 52 of 2022 (ISO week)+ const week1 = formatDateTimeWithUnit("2023-01-02", "week-of-year"); // Monday Jan 2 is week 1+ expect(week1).toMatch(/^1[a-z]+$/);++ // Mid-year dates+ const midYear = formatDateTimeWithUnit("2023-06-15", "week-of-year");+ expect(midYear).toMatch(/^2[0-9][a-z]+$/);++ // End of year+ const endYear = formatDateTimeWithUnit("2023-12-25", "week-of-year");+ expect(endYear).toMatch(/^5[0-3][a-z]+$/);+ });});});@@ -854,3 +908,14 @@ describe("formatting", () => {});});});++function setSpanishLocale() {+ // globally set locale to es+ require("dayjs/locale/es");+ dayjs.locale("es");+ dayjs.updateLocale(dayjs.locale(), { weekStart: 0 });+}++function resetLocale() {+ dayjs.locale("en");+}diff --git a/frontend/test/metabase/lib/time.unit.spec.js b/frontend/test/metabase/lib/time.unit.spec.jsindex 6d868b2b626..2dd22cbd16e 100644--- a/frontend/test/metabase/lib/time.unit.spec.js+++ b/frontend/test/metabase/lib/time.unit.spec.js@@ -1,16 +1,16 @@-import moment from "moment-timezone"; // eslint-disable-line no-restricted-imports -- deprecated usage+import dayjs from "dayjs";-import { parseTime, parseTimestamp } from "metabase/lib/time";+import { parseTime, parseTimestamp } from "metabase/lib/time-dayjs";describe("time", () => {afterEach(() => {- moment.updateLocale(moment.locale(), { week: { dow: 0 } });+ dayjs.updateLocale(dayjs.locale(), { week: { dow: 0 } });});describe("parseTimestamp", () => {- const NY15_TOKYO = moment(1420038000000); // 2014-12-31 15:00 UTC- const NY15_UTC = moment(1420070400000); // 2015-01-01 00:00 UTC- const NY15_LA = moment(1420099200000); // 2015-01-01 00:00 UTC+ const NY15_TOKYO = dayjs(1420038000000); // 2014-12-31 15:00 UTC+ const NY15_UTC = dayjs(1420070400000); // 2015-01-01 00:00 UTC+ const NY15_LA = dayjs(1420099200000); // 2015-01-01 00:00 UTCconst TEST_CASES = [["2015-01-01T00:00:00.000Z", 0, NY15_UTC],@@ -31,19 +31,19 @@ describe("time", () => {["2015-01-01T00:00:00-0800", -480, NY15_LA],];- TEST_CASES.map(([str, expectedOffset, expectedMoment]) => {+ TEST_CASES.map(([str, expectedOffset, expectedDate]) => {it(str +- " should be parsed as moment reprsenting " +- expectedMoment ++ " should be parsed as dayjs representing " ++ expectedDate +" with the offset " +expectedOffset,() => {const result = parseTimestamp(str);- expect(moment.isMoment(result)).toBe(true);+ expect(dayjs.isDayjs(result)).toBe(true);expect(result.utcOffset()).toBe(expectedOffset);- expect(result.unix()).toEqual(expectedMoment.unix());+ expect(result.unix()).toEqual(expectedDate.unix());},);});@@ -51,14 +51,14 @@ describe("time", () => {// See https://github.com/metabase/metabase/issues/11615it("parse sqlite date with unit=year correctly", () => {const result = parseTimestamp("2015-01-01", "year");- expect(moment.isMoment(result)).toBe(true);+ expect(dayjs.isDayjs(result)).toBe(true);expect(result.unix()).toEqual(NY15_UTC.unix());});it("should parse week of year correctly", () => {const daysOfWeek = [0, 1, 2, 3, 4, 5, 6];daysOfWeek.forEach((dayOfWeek) => {- moment.updateLocale(moment.locale(), { week: { dow: dayOfWeek } });+ dayjs.updateLocale(dayjs.locale(), { week: { dow: dayOfWeek } });expect(parseTimestamp(1, "week-of-year").isoWeek()).toBe(1);expect(parseTimestamp(2, "week-of-year").isoWeek()).toBe(2);expect(parseTimestamp(52, "week-of-year").isoWeek()).toBe(52);@@ -84,7 +84,7 @@ describe("time", () => {`parseTime(%p) to be %p`,(value, resultStr) => {const result = parseTime(value);- expect(moment.isMoment(result)).toBe(true);+ expect(dayjs.isDayjs(result)).toBe(true);expect(result.format("h:mm A")).toBe(resultStr);},);diff --git a/package.json b/package.jsonindex 66bcecab958..5d1b76498e8 100644--- a/package.json+++ b/package.json@@ -69,7 +69,7 @@"csv-stringify": "^6.5.0","d3": "^7.9.0","d3-scale": "^4.0.2",- "dayjs": "^1.10.4",+ "dayjs": "^1.11.18","detect-package-manager": "^3.0.2","diff": "^3.2.0","echarts": "^5.5.1-rc.1",diff --git a/yarn.lock b/yarn.lockindex ab2e9748971..32a2c140c5e 100644--- a/yarn.lock+++ b/yarn.lock@@ -9046,6 +9046,11 @@ dayjs@^1.10.4:resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.0.tgz#009bf7ef2e2ea2d5db2e6583d2d39a4b5061e805"integrity sha512-JLC809s6Y948/FuCZPm5IX8rRhQwOiyMb2TfVVQEixG7P8Lm/gt5S7yoQZmC8x1UehI9Pb7sksEt4xx14m+7Ug==+dayjs@^1.11.18:+ version "1.11.18"+ resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.18.tgz#835fa712aac52ab9dec8b1494098774ed7070a11"+ integrity sha512-zFBQ7WFRvVRhKcWoUh+ZA1g2HVgUbsZm9sbddh8EC5iv93sui8DVVz1Npvz+r6meo9VKfa8NyLWBsQK1VvIKPA==+deasync@^0.1.0:version "0.1.29"resolved "https://registry.yarnpkg.com/deasync/-/deasync-0.1.29.tgz#8bbbf9d0b235c561b36edd440b6272f1de6c572c"