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
replace moment with dayjs in cljs (#66914)
Uladzimir Havenchyk423aafea9980
diff --git a/e2e/test-host-app/shared/compatibility.cy.spec.js b/e2e/test-host-app/shared/compatibility.cy.spec.jsindex cdb66f3d3f6..3a196e27bfb 100644--- a/e2e/test-host-app/shared/compatibility.cy.spec.js+++ b/e2e/test-host-app/shared/compatibility.cy.spec.js@@ -48,7 +48,7 @@ describe("Embedding SDK: shared Host Apps compatibility tests", () => {});});- it("should load a moment locale", () => {+ it("should load a dayjs locale in date picker", () => {const time = new Date("2025-01-01");cy.clock(time, ["Date"]);@@ -68,7 +68,7 @@ describe("Embedding SDK: shared Host Apps compatibility tests", () => {});cy.findByTestId("date-filter-picker").within(() => {- cy.findByText(/^dic\..*2024/).should("exist");+ cy.findByText(/^dic.*2024/).should("exist");});});diff --git a/frontend/src/metabase-lib/filter.ts b/frontend/src/metabase-lib/filter.tsindex e860c0e7f8e..5be513a5cf9 100644--- a/frontend/src/metabase-lib/filter.ts+++ b/frontend/src/metabase-lib/filter.ts@@ -1,5 +1,4 @@-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 * as ML from "cljs/metabase.lib.js";import type { CardId } from "metabase-types/api";@@ -144,12 +143,7 @@ export function specificDateFilterClause({values,hasTime,}: SpecificDateFilterParts): ExpressionClause {- return ML.specific_date_filter_clause(- operator,- column,- values.map((value) => dayjs(value)),- hasTime,- );+ return ML.specific_date_filter_clause(operator, column, values, hasTime);}export function specificDateFilterParts(@@ -157,20 +151,7 @@ export function specificDateFilterParts(stageIndex: number,filterClause: Filterable,): SpecificDateFilterParts | null {- const filterParts = ML.specific_date_filter_parts(- query,- stageIndex,- filterClause,- );- if (!filterParts) {- return null;- }- return {- ...filterParts,- values: filterParts.values.map((value: Moment) =>- value.local(true).toDate(),- ),- };+ return ML.specific_date_filter_parts(query, stageIndex, filterClause);}export function relativeDateFilterClause({@@ -239,7 +220,7 @@ export function timeFilterParts(}return {...filterParts,- values: filterParts.values.map((value: Moment) => value.toDate()),+ values: filterParts.values.map((value: Dayjs) => value.toDate()),};}diff --git a/frontend/src/metabase/lib/i18n.js b/frontend/src/metabase/lib/i18n.jsindex 60ee4159ba6..0600d595420 100644--- a/frontend/src/metabase/lib/i18n.js+++ b/frontend/src/metabase/lib/i18n.js@@ -1,5 +1,4 @@import dayjs from "dayjs";-import moment from "moment-timezone"; // eslint-disable-line no-restricted-imports -- deprecated usageimport { addLocale, useLocale } from "ttag";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";@@ -37,17 +36,16 @@ export async function loadLocalization(locale) {return translationsObject;}-// Tell moment.js and dayjs to use the value of the start-of-week Setting for its current locale-// Moment.js dow range Sunday (0) - Saturday (6)+// Tell dayjs to use the value of the start-of-week Setting for its current locale+// range Sunday (0) - Saturday (6)export function updateStartOfWeek(startOfWeekDayName) {const startOfWeekDay = getStartOfWeekDay(startOfWeekDayName);if (startOfWeekDay != null) {- moment.updateLocale(moment.locale(), { week: { dow: startOfWeekDay } });dayjs.updateLocale(dayjs.locale(), { weekStart: startOfWeekDay });}}-// if the start of week Setting is updated, update the moment start of week+// if the start of week Setting is updated, update the dayjs start of weekMetabaseSettings.on("start-of-week", updateStartOfWeek);function setLanguage(translationsObject) {@@ -65,27 +63,11 @@ const ARABIC_LOCALES = ["ar", "ar-sa"];export function setLocalization(translationsObject) {const language = translationsObject.headers.language;setLanguage(translationsObject);- updateMomentLocale(language);updateDayjsLocale(language);updateStartOfWeek(MetabaseSettings.get("start-of-week"));if (ARABIC_LOCALES.includes(language)) {- preverseLatinNumbersInMomentLocale(language);- preverseLatinNumbersInDayjsLocale(language);- }-}--function updateMomentLocale(language) {- const locale = getLocale(language);-- try {- if (locale !== "en") {- require(`moment/locale/${locale}.js`);- }- moment.locale(locale);- } catch (e) {- console.warn(`Could not set moment.js locale to ${locale}`);- moment.locale("en");+ preserveLatinNumbersInDayjsLocale(language);}}@@ -93,18 +75,10 @@ function updateMomentLocale(language) {* Ensures that we consistently use latin numbers in Arabic locales.* See https://github.com/metabase/metabase/issues/34271*/-function preverseLatinNumbersInMomentLocale(locale) {- moment.updateLocale(locale, {+function preserveLatinNumbersInDayjsLocale(locale) {+ dayjs.updateLocale(locale, {// Preserve latin numbers, but still replace commas.// See https://github.com/moment/moment/blob/000ac1800e620f770f4eb31b5ae908f6167b0ab2/locale/ar.js#L185- postformat: (string) =>- string.replace(/\d/g, (match) => match).replace(/,/g, "،"),- });-}--// a copy of moment function-function preverseLatinNumbersInDayjsLocale(locale) {- dayjs.updateLocale(locale, {postformat(string) {return string.replace(/,/g, "،");},diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.tsindex 4155579ed74..708221db4a3 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/events.ts@@ -66,6 +66,7 @@ import Question from "metabase-lib/v1/Question";import type Metadata from "metabase-lib/v1/metadata/Metadata";import { isNative } from "metabase-lib/v1/queries/utils/card";import { getColumnKey } from "metabase-lib/v1/queries/utils/column-key";+import { isDate } from "metabase-lib/v1/types/utils/isa";import type {CardDisplayType,CardId,@@ -140,7 +141,15 @@ export const getEventDimensions = (const dimensions: ClickObjectDimension[] = [];if (hasDimensionValue) {- const dimensionValue = datum[X_AXIS_DATA_KEY];+ let dimensionValue = datum[X_AXIS_DATA_KEY];++ if (isDate(dimensionColumn) && dimensionValue != null) {+ const parsed = parseTimestamp(dimensionValue);+ if (parsed.isValid()) {+ dimensionValue = parsed.format("YYYY-MM-DDTHH:mm:ss");+ }+ }+dimensions.push({column: dimensionColumn,value: dimensionValue,diff --git a/src/metabase/lib/fe_util.cljc b/src/metabase/lib/fe_util.cljcindex 4b25feb7678..e247ab9c323 100644--- a/src/metabase/lib/fe_util.cljc+++ b/src/metabase/lib/fe_util.cljc@@ -507,7 +507,7 @@with-time? :- [:maybe :boolean]](let [column (cond-> columnwith-time? (lib.temporal-bucket/with-temporal-bucket :minute))- values (mapv #(u.time/format-for-base-type % (if with-time? :type/DateTime :type/Date)) values)]+ values (mapv #(u.time/format-date-for-filter % with-time?) values)](expression-clause operator (into [column] values) {})))(mu/defn specific-date-filter-parts :- [:maybe SpecificDateFilterParts]diff --git a/src/metabase/lib/js.cljs b/src/metabase/lib/js.cljsindex e4521600e72..10f3b600964 100644--- a/src/metabase/lib/js.cljs+++ b/src/metabase/lib/js.cljs@@ -1163,7 +1163,7 @@(let [{:keys [operator column values with-time?]} filter-parts]#js {:operator (name operator):column column- :values (to-array (map clj->js values))+ :values (to-array (map u.time/dayjs-utc->local-date values)):hasTime with-time?})))(defn ^:export relative-date-filter-clausediff --git a/src/metabase/lib/schema/expression/temporal.cljc b/src/metabase/lib/schema/expression/temporal.cljcindex 3e318b504be..37348df3af0 100644--- a/src/metabase/lib/schema/expression/temporal.cljc+++ b/src/metabase/lib/schema/expression/temporal.cljc@@ -13,18 +13,9 @@[metabase.util.malli.registry :as mr][metabase.util.performance :refer [some #?(:clj doseq) #?(:clj for)]][metabase.util.time.impl-common :as u.time.impl-common])- #?@- (:clj- [(:import- (java.time ZoneId))]- :cljs- [(:require- ["moment" :as moment]- ["moment-timezone" :as mtz])]))--#?(:cljs- ;; so the moment-timezone stuff gets loaded- (comment mtz/keep-me))+ #?(:clj+ (:import+ (java.time ZoneId))))(mbql-clause/define-tuple-mbql-clause :interval :- :type/Interval:int@@ -175,23 +166,34 @@;; argument. But we can't refactor everything in one go, so that will have to be a future refactor.[:mode [:? [:schema [:ref ::week-mode]]]])+#?(:cljs+ (defn- valid-timezone-id?+ "Check if a string is a valid timezone ID by trying to construct a DateTimeFormat with it."+ [s]+ (try+ (js/Intl.DateTimeFormat. "en-US" #js {:timeZone s})+ true+ (catch js/Error _+ false))))+(mr/def ::timezone-id[:and::common/non-blank-string[:or- (into [:enum- {:error/message "valid timezone ID"- :error/fn (fn [{:keys [value]} _]- (str "invalid timezone ID: " (pr-str value)))- :description "A valid timezone ID like: \"Asia/Aden\", \"America/Cuiaba\"."- ;; The timezone list is dynamic which make the .github/workflows/openapi-check.yml flaky on CI- ;; so we need to hack this to write a static schema- :json-schema {:type "string"}}]- (sort- #?(;; 600 timezones on java 17- :clj (ZoneId/getAvailableZoneIds)- ;; 596 timezones on moment-timezone 0.5.38- :cljs (.names (.-tz moment)))))+ #?(:clj (into [:enum+ {:error/message "valid timezone ID"+ :error/fn (fn [{:keys [value]} _]+ (str "invalid timezone ID: " (pr-str value)))+ :description "A valid timezone ID like: \"Asia/Aden\", \"America/Cuiaba\"."+ ;; The timezone list is dynamic which make the .github/workflows/openapi-check.yml flaky on CI+ ;; so we need to hack this to write a static schema+ :json-schema {:type "string"}}]+ (sort (ZoneId/getAvailableZoneIds)))+ :cljs [:fn+ {:error/message "valid timezone ID"+ :error/fn (fn [{:keys [value]} _]+ (str "invalid timezone ID: " (pr-str value)))}+ valid-timezone-id?])::literal/string.zone-offset]])(mbql-clause/define-catn-mbql-clause :convert-timezonediff --git a/src/metabase/parameters/shared.cljc b/src/metabase/parameters/shared.cljcindex 6ba73f6f9d6..df6ecd72281 100644--- a/src/metabase/parameters/shared.cljc+++ b/src/metabase/parameters/shared.cljc@@ -7,7 +7,9 @@[metabase.util.date-2.parse.builder :as b][metabase.util.i18n.impl :as i18n.impl]))#?@(:cljs- (["moment" :as moment]))+ (["dayjs" :as dayjs]+ ["dayjs/plugin/customParseFormat" :as dayjs-customParseFormat]+ ["dayjs/plugin/quarterOfYear" :as dayjs-quarterOfYear]))[clojure.string :as str][metabase.lib.core :as lib][metabase.parameters.schema :as parameters.schema]@@ -19,8 +21,11 @@#?@(:clj((java.time.format DateTimeFormatter)))))-;; Without this comment, the namespace-checker linter incorrectly detects moment as unused-#?(:cljs (comment moment/keep-me))+;; Initialize dayjs plugins+#?(:cljs+ (do+ (dayjs/extend dayjs-customParseFormat)+ (dayjs/extend dayjs-quarterOfYear)))(defmulti formatted-value"Formats a value appropriately for inclusion in a text card, based on its type. Does not do any escaping.@@ -39,14 +44,14 @@;; TODO: Refactor to use time/parse-unit and time/format-unit(defmethod formatted-value :date/single[_ value locale]- #?(:cljs (let [m (.locale (moment value) locale)]+ #?(:cljs (let [m (.locale (dayjs value) locale)](.format m "MMMM D, YYYY")):clj (u.date/format "MMMM d, yyyy" (u.date/parse value) locale)));; TODO: Refactor to use time/parse-unit and time/format-unit(defmethod formatted-value :date/month-year[_ value locale]- #?(:cljs (let [m (.locale (moment value "YYYY-MM") locale)]+ #?(:cljs (let [m (.locale (dayjs value "YYYY-MM") locale)](if (.isValid m) (.format m "MMMM, YYYY") "")):clj (u.date/format "MMMM, yyyy" (u.date/parse value) locale)))@@ -63,7 +68,7 @@;; TODO: Refactor to use time/parse-unit and time/format-unit(defmethod formatted-value :date/quarter-year[_ value locale]- #?(:cljs (let [m (.locale (moment value "[Q]Q-YYYY") locale)]+ #?(:cljs (let [m (.locale (dayjs value "[Q]Q-YYYY") locale)](if (.isValid m) (.format m "[Q]Q, YYYY") "")):clj (.format (.withLocale ^DateTimeFormatter quarter-formatter-out (i18n.impl/locale locale))(.parse ^DateTimeFormatter quarter-formatter-in value))))diff --git a/src/metabase/util/formatting/internal/date_builder.cljc b/src/metabase/util/formatting/internal/date_builder.cljcindex b53d1896a21..7f62d2201f5 100644--- a/src/metabase/util/formatting/internal/date_builder.cljc+++ b/src/metabase/util/formatting/internal/date_builder.cljc@@ -42,7 +42,10 @@:minute-dd "mm" ; 07, 39:second-dd "ss" ; 08, 45:millisecond-ddd "SSS" ; 001, 423- :day-of-year #?(:cljs "DDD" :clj "D") ; 235+ ;; Day of year: In Java we use "D". In CLJS we use a placeholder that will be replaced+ ;; by special handling in the formatter since dayjs doesn't have a format token for day-of-year.+ ;; The placeholder is escaped with [] so dayjs doesn't interpret it as format tokens.+ :day-of-year #?(:cljs "[__DAY_OF_YEAR__]" :clj "D") ; 235:week-of-year #?(:cljs "wo" :clj "w")}) ; 34th in CLJS, 34 in CLJ. No ordinal numbers in Java.(defn- format-string-literal [lit]@@ -64,6 +67,10 @@{:bad-element fmt:format format-list}))))fmt-str (apply str parts)]- #?(:cljs #(.format % fmt-str)+ #?(:cljs (if (str/includes? fmt-str "__DAY_OF_YEAR__")+ ;; Special handling for day-of-year since dayjs doesn't have a format token for it+ (fn [^js t]+ (str/replace (.format t fmt-str) "__DAY_OF_YEAR__" (str (.dayOfYear t))))+ #(.format % fmt-str)):clj (let [formatter (DateTimeFormatter/ofPattern fmt-str)]#(.format formatter %)))))diff --git a/src/metabase/util/time.cljc b/src/metabase/util/time.cljcindex a89787747bd..37166b6d484 100644--- a/src/metabase/util/time.cljc+++ b/src/metabase/util/time.cljc@@ -35,6 +35,7 @@addextractformat-for-base-type+ format-date-for-filterlocal-datelocal-date-timelocal-time])@@ -126,3 +127,12 @@:cljs js/parseInt)(str/split date-str #"-|:|T"))](into parts (repeat (- 6 (count parts)) 0))))++#?(:cljs+ (defn dayjs-utc->local-date+ "Convert a dayjs UTC value to a JavaScript Date in local time, preserving the time values.+ This is needed because coerce-to-timestamp returns dayjs objects in UTC mode, but the FE expects+ Date objects in local time with the same year/month/day/hour/minute/second values.+ dayjs.local(true) doesn't work like moment.local(true), so we format and reparse as local time."+ [value]+ (internal/dayjs-utc->local-date value)))diff --git a/src/metabase/util/time/impl.clj b/src/metabase/util/time/impl.cljindex 559b41ae51e..ba1eb71d663 100644--- a/src/metabase/util/time/impl.clj+++ b/src/metabase/util/time/impl.clj@@ -522,6 +522,17 @@:type/Date "yyyy-MM-dd")](t/format format t))))+(defn format-date-for-filter+ "Format a value as a date or datetime string for filter clauses.+ See CLJS implementation for full behavior - this JVM version just formats."+ [t with-time?]+ (if (string? t)+ t+ (let [format (if with-time?+ "yyyy-MM-dd'T'HH:mm:ss"+ "yyyy-MM-dd")]+ (t/format format t))))+(defn extract"Extract a field such as `:minute-of-hour` from a temporal value `t`."[t unit]diff --git a/src/metabase/util/time/impl.cljs b/src/metabase/util/time/impl.cljsindex d696b9d4205..4ef8be87376 100644--- a/src/metabase/util/time/impl.cljs+++ b/src/metabase/util/time/impl.cljs@@ -1,27 +1,89 @@(ns metabase.util.time.impl- "CLJS implementation of the time utilities on top of Moment.js.+ "CLJS implementation of the time utilities on top of Day.js.See [[metabase.util.time]] for the public interface."(:require- ["moment" :as moment]+ ["dayjs" :as dayjs]+ ;; Locale imports for all Metabase-supported locales.+ ;; These must be imported for .locale() calls to work in CLJS.+ ["dayjs/locale/ar"]+ ["dayjs/locale/ar-sa"]+ ["dayjs/locale/bg"]+ ["dayjs/locale/ca"]+ ["dayjs/locale/cs"]+ ["dayjs/locale/da"]+ ["dayjs/locale/de"]+ ["dayjs/locale/es"]+ ["dayjs/locale/fa"]+ ["dayjs/locale/fi"]+ ["dayjs/locale/fr"]+ ["dayjs/locale/he"]+ ["dayjs/locale/hu"]+ ["dayjs/locale/id"]+ ["dayjs/locale/it"]+ ["dayjs/locale/ja"]+ ["dayjs/locale/ko"]+ ["dayjs/locale/lv"]+ ["dayjs/locale/ms"]+ ["dayjs/locale/nb"]+ ["dayjs/locale/nl"]+ ["dayjs/locale/pl"]+ ["dayjs/locale/pt-br"]+ ["dayjs/locale/ru"]+ ["dayjs/locale/sk"]+ ["dayjs/locale/sl"]+ ["dayjs/locale/sq"]+ ["dayjs/locale/sr"]+ ["dayjs/locale/sv"]+ ["dayjs/locale/tr"]+ ["dayjs/locale/uk"]+ ["dayjs/locale/vi"]+ ["dayjs/locale/zh-cn"]+ ["dayjs/locale/zh-hk"]+ ["dayjs/locale/zh-tw"]+ ["dayjs/plugin/advancedFormat" :as advancedFormat]+ ["dayjs/plugin/customParseFormat" :as customParseFormat]+ ["dayjs/plugin/dayOfYear" :as dayOfYear]+ ["dayjs/plugin/isoWeek" :as isoWeek]+ ["dayjs/plugin/localeData" :as localeData]+ ["dayjs/plugin/objectSupport" :as objectSupport]+ ["dayjs/plugin/quarterOfYear" :as quarterOfYear]+ ["dayjs/plugin/utc" :as utc]+ ["dayjs/plugin/weekOfYear" :as weekOfYear]+ ;; cljfmt reorders these namespaces to be out of order, then kondo complains about it.+ ;; so let's just live with the 1 unordered namespace require for now. :skull:+ ^{:clj-kondo/ignore [:unsorted-required-namespaces]}+ ["dayjs/plugin/weekday" :as weekday][metabase.util.time.impl-common :as common]))-(defn- now [] (moment))+;; Initialize dayjs plugins+(dayjs/extend advancedFormat)+(dayjs/extend customParseFormat)+(dayjs/extend dayOfYear)+(dayjs/extend isoWeek)+(dayjs/extend localeData)+(dayjs/extend objectSupport)+(dayjs/extend quarterOfYear)+(dayjs/extend utc)+(dayjs/extend weekday)+(dayjs/extend weekOfYear)++(defn- now [] (dayjs));;; ----------------------------------------------- predicates -------------------------------------------------------(defn datetime?- "Given any value, check if it's a (possibly invalid) Moment."+ "Given any value, check if it's a Day.js instance."[value]- (and value (moment/isMoment value)))+ (and value (dayjs/isDayjs value)))-(defn time?- "checks if the provided value is a local time value."- [value]- (moment/isMoment value))+(def time?+ "Checks if the provided value is a local time value.+ In Day.js, times are represented as full datetime instances."+ datetime?)(defn valid?- "Given a Moment, check that it's valid."+ "Given a Day.js instance, check that it's valid."[value]- (and (datetime? value) (.isValid ^moment/Moment value)))+ (and (datetime? value) (.isValid ^dayjs value)))(defn normalize"Does nothing. Just a placeholder in CLJS; the JVM implementation does some real work."@@ -30,26 +92,26 @@(defn same-day?"Given two platform-specific datetimes, checks if they fall within the same day."- [^moment/Moment d1 ^moment/Moment d2]+ [^dayjs d1 ^dayjs d2](.isSame d1 d2 "day"))(defn same-month?"True if these two datetimes fall in the same (year and) month."- [^moment/Moment d1 ^moment/Moment d2]+ [^dayjs d1 ^dayjs d2](.isSame d1 d2 "month"))(defn same-year?"True if these two datetimes fall in the same year."- [^moment/Moment d1 ^moment/Moment d2]+ [^dayjs d1 ^dayjs d2](.isSame d1 d2 "year"));;; ---------------------------------------------- information -------------------------------------------------------(defn first-day-of-week"The first day of the week varies by locale, but Metabase has a setting that overrides it.- In CLJS, Moment is already configured with that setting."+ In CLJS, Day.js is already configured with that setting."[](nth [:sunday :monday :tuesday :wednesday :thursday :friday :saturday]- (.firstDayOfWeek (moment/localeData))))+ (.firstDayOfWeek (dayjs/localeData))))(def default-options"The default map of options - empty in CLJS."@@ -57,27 +119,58 @@;;; ------------------------------------------------ to-range --------------------------------------------------------(defn- apply-offset- [^moment/Moment value offset-n offset-unit]+ [value offset-n offset-unit](.add- (moment value)+ (dayjs value)offset-n(name offset-unit)))-(defmethod common/to-range :default [^moment/Moment value {:keys [n unit]}]- (let [^moment/Moment c1 (.clone value)- ^moment/Moment c2 (.clone value)- ^moment/Moment adjusted (if (> n 1)- (.add c2 (dec n) (name unit))- c2)]- [(.startOf c1 (name unit))- (.endOf adjusted (name unit))]))+(defmethod common/to-range :default [^dayjs value {:keys [n unit]}]+ (let [^dayjs adjusted (if (> n 1)+ (.add value (dec n) (name unit))+ value)]+ [(.startOf value (name unit))+ (.endOf adjusted (name unit))]))-;; NB: Only the :default for to-range is needed in CLJS, since Moment's startOf and endOf methods are doing the work.+;; NB: Only the :default for to-range is needed in CLJS, since Day.js's startOf and endOf methods are doing the work.;;; -------------------------------------------- string->timestamp ---------------------------------------------------+(defn- valid-date-string?+ "Check if a date string is a valid ISO-8601 format.+ Rejects invalid dates like '2024-01-99' by validating the date components."+ [value]+ (when (string? value)+ ;; Parse with dayjs and check if it matches one of our expected formats+ ;; AND that the formatted output matches the input (to catch invalid dates)+ (let [parsed (.utc dayjs value)]+ (when (.isValid parsed)+ ;; Check for invalid dates by comparing input with formatted output+ ;; For "2024-01-99", dayjs would roll over to April, so format would differ+ ;; Note: re-find without groups returns a string, not a vector+ (let [input-date-part (re-find #"^\d{4}-\d{2}-\d{2}" value)+ output-date-part (.format parsed "YYYY-MM-DD")]+ (or (nil? input-date-part) ;; If no date part found, it's a time-only or other format+ (= input-date-part output-date-part)))))))+(defmethod common/string->timestamp :default [value _];; Best effort to parse this unknown string format, as a local zoneless datetime, then treating it as UTC.- (moment/utc value moment/ISO_8601))+ ;; Validate the date to reject invalid dates like "2024-01-99"+ (when (valid-date-string? value)+ (.utc dayjs value)))++(def ^:private day-name->iso-weekday+ "Map of day names (case-insensitive) to ISO weekday numbers (Monday=1, Sunday=7)."+ {"mon" 1 "monday" 1+ "tue" 2 "tuesday" 2+ "wed" 3 "wednesday" 3+ "thu" 4 "thursday" 4+ "fri" 5 "friday" 5+ "sat" 6 "saturday" 6+ "sun" 7 "sunday" 7})++(defn- parse-day-name [value]+ (when (string? value)+ (get day-name->iso-weekday (.toLowerCase value))))(defmethod common/string->timestamp :day-of-week [value options];; Try to parse as a regular timestamp; if that fails then try to treat it as a weekday name and adjust from@@ -86,133 +179,160 @@(catch js/Error _ nil))](if (valid? as-default)as-default- (-> (now)- (.isoWeekday value)- (.startOf "day")))))+ ;; dayjs's isoWeekday only accepts numbers, so we need to convert day names to numbers+ (when-let [iso-weekday (parse-day-name value)]+ (-> (now)+ (.isoWeekday iso-weekday)+ (.startOf "day"))))));;; -------------------------------------------- number->timestamp ---------------------------------------------------(defn- magic-base-date"Some of the date coercions are relative, and not directly involved with any particular month.To avoid errors we need to use a reference date that is (a) in a month with 31 days,(b) in a leap year.This uses 2016-01-01 for the purpose.- This is a function that returns fresh values, since Moments are mutable."+ This is a function that returns fresh values, since we want a consistent reference."[]- (moment "2016-01-01"))+ (dayjs "2016-01-01"))(defmethod common/number->timestamp :default [value _];; If no unit is given, or the unit is not recognized, try to parse the number as year number, returning the timestamp;; for midnight UTC on January 1.- (moment/utc value moment/ISO_8601))+ ;; We need to pass it as a string to avoid dayjs treating it as a Unix timestamp+ (.utc dayjs (str value)))(defmethod common/number->timestamp :minute-of-hour [value _]- (.. (now) (minute value) (startOf "minute")))+ (-> (now) (.minute value) (.startOf "minute")))(defmethod common/number->timestamp :hour-of-day [value _]- (.. (now) (hour value) (startOf "hour")))+ (-> (now) (.hour value) (.startOf "hour")))(defmethod common/number->timestamp :day-of-week [value _];; Metabase uses 1 to mean the start of the week, based on the Metabase setting for the first day of the week.- ;; Moment uses 0 as the first day of the week in its configured locale.- (.. (now) (weekday (dec value)) (startOf "day")))+ ;; Day.js's weekday() uses 0 as the first day of the week in its configured locale.+ (-> (now) (.weekday (dec value)) (.startOf "day")))(defmethod common/number->timestamp :day-of-week-iso [value _]- (.. (now) (isoWeekday value) (startOf "day")))+ (-> (now) (.isoWeekday value) (.startOf "day")))(defmethod common/number->timestamp :day-of-month [value _];; We force the initial date to be in a month with 31 days.- (.. (magic-base-date) (date value) (startOf "day")))+ (-> (magic-base-date) (.date value) (.startOf "day")))(defmethod common/number->timestamp :day-of-year [value _];; We force the initial date to be in a leap year (2016).- (.. (magic-base-date) (dayOfYear value) (startOf "day")))+ (-> (magic-base-date) (.dayOfYear value) (.startOf "day")))(defmethod common/number->timestamp :week-of-year [value _]- (.. (now) (week value) (startOf "week")))+ (-> (now) (.week value) (.startOf "week")))(defmethod common/number->timestamp :month-of-year [value _]- (.. (now) (month (dec value)) (startOf "month")))+ ;; Day.js uses 0-based months, so we need to subtract 1+ (-> (now) (.month (dec value)) (.startOf "month")))(defmethod common/number->timestamp :quarter-of-year [value _]- (.. (now) (quarter value) (startOf "quarter")))+ (-> (now) (.quarter value) (.startOf "quarter")))(defmethod common/number->timestamp :year [value _]- (.. (now) (year value) (startOf "year")))+ (-> (now) (.year value) (.startOf "year")));;; ---------------------------------------------- parsing helpers ---------------------------------------------------(defn parse-with-zone"Parses a timestamp with Z or a timezone offset at the end.- This requires a different API call from timestamps without time zones in CLJS."+ Dayjs will handle this correctly with utc() and keepOffset."[value]- (moment/parseZone value))+ (let [;; Check if it has a timezone offset+ has-offset? (re-find #"[Zz]|[+-]\d{2}:?\d{2}$" value)]+ (if has-offset?+ ;; Parse as UTC and keep the offset info+ (.utc dayjs value true)+ ;; No timezone, parse normally+ (dayjs value))))(defn localize- "Given a freshly parsed absolute Moment, convert it to a local one."+ "Given a freshly parsed absolute Day.js instance, convert it to a local one."[value](.local value))(def ^:private parse-time-formats- #js ["HH:mm:ss.SSSZ"- "HH:mm:ss.SSS"+ #js ["HH:mm:ss.SSS""HH:mm:ss""HH:mm"])(defn parse-time-string"Parses a time string that has been stripped of any time zone."[value]- (moment value parse-time-formats))+ (dayjs value parse-time-formats));;; ----------------------------------------------- constructors -----------------------------------------------------(defn local-time- "Constructs a platform time value (eg. Moment, LocalTime) for the given hour and minute, plus optional seconds and+ "Constructs a platform time value (eg. Day.js, LocalTime) for the given hour and minute, plus optional seconds andmilliseconds.If called without arguments, returns the current time."([]- ;; Actually a full datetime, but Moment doesn't have freestanding time values.- (moment))+ ;; Actually a full datetime, but Day.js doesn't have freestanding time values.+ (dayjs))([hours minutes]- (moment #js {:hours hours, :minutes minutes}))+ (dayjs #js {:hour hours, :minute minutes}))([hours minutes seconds]- (moment #js {:hours hours, :minutes minutes, :seconds seconds}))+ (dayjs #js {:hour hours, :minute minutes, :second seconds}))([hours minutes seconds millis]- (moment #js {:hours hours, :minutes minutes, :seconds seconds, :milliseconds millis})))+ (dayjs #js {:hour hours, :minute minutes, :second seconds, :millisecond millis})))(declare truncate)(defn local-date- "Constructs a platform date value (eg. Moment, LocalDate) for the given year, month and day.+ "Constructs a platform date value (eg. Day.js, LocalDate) for the given year, month and day.Day is 1-31. January = 1, or you can specify keywords like `:jan`, `:jun`."- ([] (truncate (moment) :day))+ ([] (truncate (dayjs) :day))([year month day]- (moment #js {:year year- :day day- ;; Moment uses 0-based months, unlike Metabase.- :month (dec (or (common/month-keywords month) month))})))+ (dayjs #js {:year year+ :date day+ ;; Day.js uses 0-based months, unlike Metabase.+ :month (dec (or (common/month-keywords month) month))})))(defn local-date-time- "Constructs a platform datetime (eg. Moment, LocalDateTime).+ "Constructs a platform datetime (eg. Day.js, LocalDateTime).Accepts either:- no arguments (current datetime)- a local date and local time (see [[local-date]] and [[local-time]]); or- year, month, day, hour, and minute, plus optional seconds and millis."- ([] (moment))+ ([] (dayjs))([a-date a-time](when-not (and (valid? a-date) (valid? a-time))- (throw (ex-info "Expected valid Moments for date and time" {:date a-date- :time a-time})))- (let [^moment/Moment d (.clone a-date)- ^moment/Moment t a-time]- (doseq [unit ["hour" "minute" "second" "millisecond"]]- (.set d unit (.get t unit)))- d))+ (throw (ex-info "Expected valid Day.js instances for date and time" {:date a-date+ :time a-time})))+ ;; Use Day.js object support plugin to set all values at once+ (dayjs #js {:year (.year ^dayjs a-date)+ :month (.month ^dayjs a-date)+ :date (.date ^dayjs a-date)+ :hour (.hour ^dayjs a-time)+ :minute (.minute ^dayjs a-time)+ :second (.second ^dayjs a-time)+ :millisecond (.millisecond ^dayjs a-time)}))([year month day hours minutes]- (local-date-time (local-date year month day) (local-time hours minutes)))+ (dayjs #js {:year year+ :month (dec (or (common/month-keywords month) month))+ :date day+ :hour hours+ :minute minutes}))([year month day hours minutes seconds]- (local-date-time (local-date year month day) (local-time hours minutes seconds)))+ (dayjs #js {:year year+ :month (dec (or (common/month-keywords month) month))+ :date day+ :hour hours+ :minute minutes+ :second seconds}))([year month day hours minutes seconds millis]- (local-date-time (local-date year month day) (local-time hours minutes seconds millis))))+ (dayjs #js {:year year+ :month (dec (or (common/month-keywords month) month))+ :date day+ :hour hours+ :minute minutes+ :second seconds+ :millisecond millis})));;; ------------------------------------------------ arithmetic ------------------------------------------------------@@ -226,9 +346,11 @@(defn- coerce-local-date-time [input](-> inputcommon/drop-trailing-time-zone- (moment/utc moment/ISO_8601)))+ (dayjs/utc)))(def ^:private unit-formats+ "Format strings for temporal units.+ Note: :day-of-year uses nil because DDD produces zero-padded output, we use dayOfYear() method instead."{:day-of-week "dddd":day-of-week-abbrev "ddd":day-of-week-iso "dddd"@@ -238,44 +360,46 @@:hour-of-day "h A":hour-of-day-24 "h":day-of-month "D"- :day-of-year "DDD"+ :day-of-year nil ;; handled specially with dayOfYear() method:week-of-year "w":quarter-of-year "[Q]Q"})(defn ^:private format-extraction-unit"Formats a date-time value given the temporal extraction unit.If unit is not supported, returns nil."- [t unit locale]- (when-some [format (get unit-formats unit)]- (if locale- (-> t- (.locale locale)- (.format format))- (.format t format))))+ [^dayjs t unit locale]+ ;; Special case for day-of-year: use the dayOfYear() method instead of format+ ;; because DDD produces zero-padded output+ (if (= unit :day-of-year)+ (str (.dayOfYear t))+ (when-some [format (get unit-formats unit)]+ (if locale+ (-> t+ (.locale locale)+ (.format format))+ (.format t format)))))(defn- has-explicit-time?- "Does this moment value have explicit time parts (i.e., what it parsed with time components?"- [m]- ;; type hints to quell warnings from compiler- (let [^js/Object flags (.parsingFlags ^moment/Moment m)- ^js/Array parts (.-parsedDateParts flags)]- (when parts- (some (fn [i] (aget parts i)) [3 ;; hours- 4 ;; minutes- 5 ;; seconds- ]))))+ "Does this Day.js value have explicit time parts?+ For Day.js we check if hour, minute or second are non-zero, since Day.js doesn't track parsed parts.+ Note: This also returns true for time 00:00 if there's no date (checked by has-explicit-date?)."+ [^dayjs m]+ (or (pos? (.hour m))+ (pos? (.minute m))+ (pos? (.second m))+ (pos? (.millisecond m))))(defn- has-explicit-date?- "Does this moment value have explicit date parts (i.e., what it parsed with date components?"- [m]- ;; type hints to quell warnings from compiler- (let [^js/Object flags (.parsingFlags ^moment/Moment m)- ^js/Array parts (.-parsedDateParts flags)]- (when parts- (some (fn [i] (aget parts i)) [0 ;; year- 1 ;; month- 2 ;; day- ]))))+ "Does this Day.js value have explicit date parts?+ For Day.js we check if the date matches today - if it does, it might be a time-only value+ where dayjs defaulted to today's date. This is a heuristic since dayjs doesn't track parsed parts."+ [^dayjs m]+ (let [^dayjs today (dayjs)]+ ;; If the date matches today and time components are not all zero,+ ;; it's likely a time-only value that defaulted to today+ (not (and (= (.year m) (.year today))+ (= (.month m) (.month today))+ (= (.date m) (.date today))))))(defn format-unit"Formats a temporal-value (iso date/time string, int for extraction units) given the temporal-bucketing unit.@@ -292,7 +416,7 @@t (cond;; Anchor to an arbitrary date since time inputs are only defined for;; :hour-of-day and :minute-of-hour.- time? (moment/utc (str "2023-01-01T" input) moment/ISO_8601)+ time? (.utc dayjs (str "2023-01-01T" input))(or date? date-time?) (coerce-local-date-time input))](if (and t (.isValid t))(or@@ -311,7 +435,7 @@(format-extraction-unit (common/number->timestamp input {:unit unit}) unit locale)(str input)))- (moment/isMoment input)+ (dayjs/isDayjs input)(or (format-extraction-unit input unit locale);; no locale for default formats(cond@@ -326,18 +450,55 @@:else ;; otherwise both date and time(.format input "MMM D, YYYY, h:mm A"))))))+(def ^:private month-abbrev->month+ "Map of English month abbreviations (case-insensitive) to month numbers (0-11)."+ {"jan" 0 "feb" 1 "mar" 2 "apr" 3 "may" 4 "jun" 5+ "jul" 6 "aug" 7 "sep" 8 "oct" 9 "nov" 10 "dec" 11})++(defn- parse-day-abbrev+ "Parse a day abbreviation like 'Wed' to a dayjs set to that weekday."+ [input]+ ;; Reuse day-name->iso-weekday and use isoWeekday for consistency+ (when-let [iso-weekday (parse-day-name input)]+ (-> (now) (.isoWeekday iso-weekday) (.startOf "day"))))++(defn- parse-month-abbrev+ "Parse a month abbreviation like 'Jan' to a dayjs set to that month."+ [input]+ (when-let [month (get month-abbrev->month (.toLowerCase input))]+ (-> (now) (.month month) (.startOf "month"))))++(defn- parse-hour-24+ "Parse an hour in 24-hour format to a dayjs set to that hour."+ [input]+ (when-let [hour (js/parseInt input 10)]+ (when (and (not (js/isNaN hour)) (>= hour 0) (< hour 24))+ (-> (now) (.hour hour) (.startOf "hour")))))+(defn parse-unit"Parse a unit of time/date, e.g., 'Wed' or 'August' or '14'."([input unit]- (when-some [format (get unit-formats unit)]- (moment input format)))+ ;; Dayjs can't parse day/month names from format strings, so we handle them manually+ (case unit+ (:day-of-week :day-of-week-abbrev)+ (parse-day-abbrev input)++ (:month-of-year :month-of-year-full)+ (parse-month-abbrev input)++ :hour-of-day-24+ (parse-hour-24 input)++ ;; For other units, try standard dayjs parsing+ (when-some [format (get unit-formats unit)]+ (dayjs input format))))([input unit locale]- (let [temp (.locale moment)] ;; 1. save current locale+ (let [temp (.locale (dayjs))] ;; 1. save current locale(try- (.locale moment locale) ;; 2. set new locale for subsequent parse+ (.locale (dayjs) locale) ;; 2. set new locale for subsequent parse(parse-unit input unit)(finally- (.locale moment temp)))))) ;; 3. set locale to original+ (.locale (dayjs) temp)))))) ;; 3. set locale to original(defn format-diff"Formats a time difference between two temporal values.@@ -362,16 +523,14 @@(let [lhs (coerce-local-date-time temporal-value-1)rhs (coerce-local-date-time temporal-value-2)year-matches? (= (.format lhs "YYYY") (.format rhs "YYYY"))- month-matches? (= (.format lhs "MMM") (.format rhs "MMM"))- day-matches? (= (.format lhs "D") (.format rhs "D"))- hour-matches? (= (.format lhs "HH") (.format rhs "HH"))+ day-matches? (and (= (.format lhs "MMM") (.format rhs "MMM"))+ (= (.format lhs "D") (.format rhs "D")))[lhs-fmt rhs-fmt] (cond- (and year-matches? month-matches? day-matches? hour-matches?)- ["MMM D, YYYY, h:mm A " " h:mm A"]-- (and year-matches? month-matches? day-matches?)+ ;; Same day: show date once, both times+ (and year-matches? day-matches?)["MMM D, YYYY, h:mm A " " h:mm A"]+ ;; Same year: abbreviate year on first valueyear-matches?["MMM D, h:mm A " " MMM D, YYYY, h:mm A"])]@@ -381,8 +540,8 @@(and (common/matches-date? temporal-value-1)(common/matches-date? temporal-value-2))- (let [lhs (moment/utc temporal-value-1 moment/ISO_8601)- rhs (moment/utc temporal-value-2 moment/ISO_8601)+ (let [lhs (.utc dayjs temporal-value-1)+ rhs (.utc dayjs temporal-value-2)year-matches? (= (.format lhs "YYYY") (.format rhs "YYYY"))month-matches? (= (.format lhs "MMM") (.format rhs "MMM"))[lhs-fmt rhs-fmt] (cond@@ -420,9 +579,15 @@(apply format-diff date-ranges))))(def ^:private temporal-formats+ "Map of temporal types to their regex patterns and dayjs format strings.+ Note: In dayjs, Z matches timezone offsets like +05:00, while [Z] matches literal 'Z'.+ We include both patterns to handle both Z and +HH:mm offsets."{:offset-date-time {:regex common/offset-datetime-regex- :formats #js ["YYYY-MM-DDTHH:mm:ss.SSSZ"+ :formats #js ["YYYY-MM-DDTHH:mm:ss.SSS[Z]"+ "YYYY-MM-DDTHH:mm:ss.SSSZ"+ "YYYY-MM-DDTHH:mm:ss[Z]""YYYY-MM-DDTHH:mm:ssZ"+ "YYYY-MM-DDTHH:mm[Z]""YYYY-MM-DDTHH:mmZ"]}:local-date-time {:regex common/local-datetime-regex:formats #js ["YYYY-MM-DDTHH:mm:ss.SSS"@@ -433,117 +598,97 @@"YYYY-MM""YYYY"]}:offset-time {:regex common/offset-time-regex- :formats #js ["HH:mm:ss.SSSZ"+ :formats #js ["HH:mm:ss.SSS[Z]"+ "HH:mm:ss.SSSZ"+ "HH:mm:ss[Z]""HH:mm:ssZ"+ "HH:mm[Z]""HH:mmZ"]}:local-time {:regex common/local-time-regex:formats #js ["HH:mm:ss.SSS""HH:mm:ss""HH:mm"]}})-(defn- iso-8601->moment+type+(defn- parse-with-formats+ "Parse a string with the given formats array. Returns a valid dayjs or nil."+ [s formats]+ (let [parsed (dayjs s formats true)] ;; true = strict mode+ (when (.isValid parsed)+ parsed)))++(defn- iso-8601->dayjs+type[s](some (fn [[value-type {:keys [regex formats]}]](when (re-matches regex s)- (let [parsed (moment/parseZone s formats #_strict? true)]- (when (.isValid parsed)+ ;; offset-date-time needs special handling for timezone preservation+ (let [parsed (if (= value-type :offset-date-time)+ (parse-with-zone s)+ (parse-with-formats s formats))]+ (when (and parsed (.isValid parsed))[parsed value-type]))))temporal-formats))-(comment- (moment "01:49:10.858Z" "HH:mm:ss.SSSZ")-- (let [s "1982-03-16T01:49:10.858Z"- formats #js ["YYYY-MM-DDTHH:mm:ss.SSS[Z]"]- formatz #js ["YYYY-MM-DDTHH:mm:ss.SSSZ"]- s-parsed (moment/parseZone s formats #_strict? true)- z-parsed (moment/parseZone s formatz #_strict? true)]- {:tz (.. (js/Intl.DateTimeFormat) resolvedOptions -timeZone)- :tzo (.getTimezoneOffset (js/Date.)) #_mins- :s s-parsed- :z z-parsed- :fz (.format z-parsed "YYYY-MM-DDTHH:mm:ss.SSSZ")- :fs (.format z-parsed "YYYY-MM-DDTHH:mm:ss.SSS[Z]")})- -)--(defmulti ^:private moment+type->iso-8601- {:arglists '([moment+type])}- (fn [[_t value-type]]- value-type))--(defmethod moment+type->iso-8601 :offset-date-time- [[^moment/Moment t _value-type]]- (let [format-string (cond- (pos? (.millisecond t)) "YYYY-MM-DDTHH:mm:ss.SSS[Z]"- (pos? (.second t)) "YYYY-MM-DDTHH:mm:ss[Z]"- :else "YYYY-MM-DDTHH:mm[Z]")]+(def ^:private iso-8601-format-strings+ "Format strings for ISO-8601 output by type and precision."+ {:offset-date-time {:millis "YYYY-MM-DDTHH:mm:ss.SSS[Z]"+ :second "YYYY-MM-DDTHH:mm:ss[Z]"+ :minute "YYYY-MM-DDTHH:mm[Z]"}+ :local-date-time {:millis "YYYY-MM-DDTHH:mm:ss.SSS"+ :second "YYYY-MM-DDTHH:mm:ss"+ :minute "YYYY-MM-DDTHH:mm"}+ :local-date {:default "YYYY-MM-DD"}+ :offset-time {:millis "HH:mm:ss.SSS[Z]"+ :second "HH:mm:ss[Z]"+ :minute "HH:mm[Z]"}+ :local-time {:millis "HH:mm:ss.SSS"+ :second "HH:mm:ss"+ :minute "HH:mm"}})++(defn- dayjs+type->iso-8601+ "Format a dayjs instance as ISO-8601 string based on its type."+ [[^dayjs t value-type]]+ (let [formats (get iso-8601-format-strings value-type)+ format-string (or (:default formats)+ (cond+ (pos? (.millisecond t)) (:millis formats)+ (pos? (.second t)) (:second formats)+ :else (:minute formats)))](.format t format-string)))-(defmethod moment+type->iso-8601 :local-date-time- [[^moment/Moment t _value-type]]- (let [format-string (cond- (pos? (.millisecond t)) "YYYY-MM-DDTHH:mm:ss.SSS"- (pos? (.second t)) "YYYY-MM-DDTHH:mm:ss"- :else "YYYY-MM-DDTHH:mm")]- (.format t format-string)))--(defmethod moment+type->iso-8601 :local-date- [[^moment/Moment t _value-type]]- (.format t "YYYY-MM-DD"))--(defmethod moment+type->iso-8601 :offset-time- [[^moment/Moment t _value-type]]- (let [format-string (cond- (pos? (.millisecond t)) "HH:mm:ss.SSS[Z]"- (pos? (.second t)) "HH:mm:ss[Z]"- :else "HH:mm[Z]")]- (.format t format-string)))--(defmethod moment+type->iso-8601 :local-time- [[^moment/Moment t _value-type]]- (let [format-string (cond- (pos? (.millisecond t)) "HH:mm:ss.SSS"- (pos? (.second t)) "HH:mm:ss"- :else "HH:mm")]- (.format t format-string)))--(defn- ->moment ^moment/Moment [t]- (if (instance? js/Date t)- (moment/utc t)- t))+(defn- ^dayjs ->dayjs+ "Convert a value to a dayjs instance. Handles strings, js/Date, and dayjs instances."+ [t]+ (cond+ (string? t) (first (iso-8601->dayjs+type t))+ (instance? js/Date t) (.utc dayjs t)+ :else t))(defn unit-diff"Return the number of `unit`s between two temporal values `before` and `after`, e.g. maybe there are 32 `:day`sbetween Jan 1st and Feb 2nd."[unit before after]- (let [^moment/Moment before (if (string? before)- (first (iso-8601->moment+type before))- (->moment before))- ^moment/Moment after (if (string? after)- (first (iso-8601->moment+type after))- (->moment after))]- (.diff after before (name unit))))+ (.diff (->dayjs after) (->dayjs before) (name unit)))++(defn- with-string-preservation+ "Apply f to a temporal value, preserving string format if input was a string."+ [t f]+ (if (string? t)+ (let [[parsed value-type] (iso-8601->dayjs+type t)]+ (dayjs+type->iso-8601 [(f parsed) value-type]))+ (f (->dayjs t))))(defn truncate- "ClojureScript implementation of [[metabase.util.time/truncate]]; supports both Moment.js instances and ISO-8601+ "ClojureScript implementation of [[metabase.util.time/truncate]]; supports both Day.js instances and ISO-8601strings."[t unit]- (if (string? t)- (let [[t value-type] (iso-8601->moment+type t)- t (truncate t unit)]- (moment+type->iso-8601 [t value-type]))- (let [^moment/Moment t (->moment t)]- (.startOf t (name unit)))))+ (with-string-preservation t (fn [^dayjs parsed]+ (.startOf parsed (name unit)))))(defn add- "ClojureScript implementation of [[metabase.util.time/add]]; supports both Moment.js instances and ISO-8601 strings."+ "ClojureScript implementation of [[metabase.util.time/add]]; supports both Day.js instances and ISO-8601 strings."[t unit amount]- (if (string? t)- (let [[t value-type] (iso-8601->moment+type t)- t (add t unit amount)]- (moment+type->iso-8601 [t value-type]))- (let [^moment/Moment t (->moment t)]- (.add t amount (name unit)))))+ (with-string-preservation t (fn [^dayjs parsed]+ (.add parsed amount (name unit)))))(defn format-for-base-type"ClojureScript implementation of [[metabase.util.time/format-for-base-type]]; format a temporal value as an ISO-8601@@ -552,18 +697,31 @@[t base-type](if (string? t)t- (let [t (->moment t)+ (let [t (->dayjs t)value-type (condp #(isa? %2 %1) base-type:type/TimeWithTZ :offset-time:type/Time :local-time:type/DateTimeWithTZ :offset-date-time:type/DateTime :local-date-time:type/Date :local-date)]- (moment+type->iso-8601 [t value-type]))))+ (dayjs+type->iso-8601 [t value-type]))))++(defn format-date-for-filter+ "Format a value as a date or datetime string for filter clauses, preserving local time.+ Unlike [[->dayjs]] which converts JS Dates to UTC, this uses local time to preserve+ the user's intended date/time values."+ [t with-time?]+ (let [d (cond+ (instance? js/Date t) (dayjs t) ; dayjs(Date) uses local time+ (string? t) (first (iso-8601->dayjs+type t))+ :else t)]+ (if with-time?+ (.format d "YYYY-MM-DDTHH:mm:ss")+ (.format d "YYYY-MM-DD"))))(defn extract"Extract a field such as `:minute-of-hour` from a temporal value `t`."- [^moment/Moment t unit]+ [^dayjs t unit](case unit:second-of-minute (.second t):minute-of-hour (.minute t)@@ -576,3 +734,15 @@:month-of-year (inc (.month t)) ;; `month` is 0-11:quarter-of-year (.quarter t):year (.year t)))++(defn dayjs-utc->local-date+ "Convert a dayjs UTC value to a JavaScript Date in local time, preserving the time values.+ This is needed because coerce-to-timestamp returns dayjs objects in UTC mode, but the FE expects+ Date objects in local time with the same year/month/day/hour/minute/second values.+ dayjs.local(true) doesn't work like moment.local(true), so we format and reparse as local time."+ [value]+ (when (valid? value)+ (-> value+ (.format "YYYY-MM-DDTHH:mm:ss.SSS")+ dayjs+ (.toDate))))diff --git a/test/metabase/parameters/shared_test.cljc b/test/metabase/parameters/shared_test.cljcindex 7aff3893cf7..0ef1a8d24d2 100644--- a/test/metabase/parameters/shared_test.cljc+++ b/test/metabase/parameters/shared_test.cljc@@ -1,5 +1,7 @@(ns metabase.parameters.shared-test(:require+ #?@(:cljs [;; Locale imports for locale-specific formatting tests+ ["dayjs/locale/es"]])[clojure.test :refer [deftest is are testing]][metabase.parameters.shared :as params]))diff --git a/test/metabase/util/time_test.cljc b/test/metabase/util/time_test.cljcindex 80e5e0f9a12..22d1a53b83c 100644--- a/test/metabase/util/time_test.cljc+++ b/test/metabase/util/time_test.cljc@@ -1,46 +1,59 @@(ns metabase.util.time-test(:require- #?@(:cljs [["moment" :as moment]- ["moment-timezone" :as moment-tz]]+ #?@(:cljs [["dayjs" :as dayjs]+ ["dayjs/plugin/customParseFormat" :as dayjs-customParseFormat]+ ["dayjs/plugin/timezone" :as dayjs-timezone]+ ["dayjs/plugin/utc" :as dayjs-utc]+ ;; Locale imports for locale-specific formatting/parsing tests+ ["dayjs/locale/fr"]+ ["dayjs/locale/de"]+ ["dayjs/locale/es"]]:clj [[java-time.api :as t]])[clojure.test :refer [are deftest is testing]][metabase.util.time :as shared.ut][metabase.util.time.impl :as internal])#?(:clj (:import java.util.Locale)))+#?(:cljs+ ;; Initialize dayjs plugins for tests+ (do+ (dayjs/extend dayjs-utc)+ (dayjs/extend dayjs-customParseFormat)+ (dayjs/extend dayjs-timezone)))+(defn- from [time-str]- #?(:cljs (moment time-str)+ #?(:cljs (dayjs time-str):clj (t/offset-date-time (t/local-date-time time-str) (t/zone-offset))))(defn- from-zulu [time-str]- #?(:cljs (moment/utc time-str)+ #?(:cljs (.utc dayjs time-str):clj (t/offset-date-time time-str)))(defn- from-local [time-str]- #?(:cljs (moment time-str)+ #?(:cljs (dayjs time-str):clj (t/local-date-time time-str)))(defn- from-local-date [time-str]- #?(:cljs (moment time-str)+ #?(:cljs (dayjs time-str):clj (t/local-date time-str)))(defn- from-local-time [time-str]- #?(:cljs (moment time-str- #js [(.. moment -HTML5_FMT -TIME_MS)- (.. moment -HTML5_FMT -TIME_SECONDS)- (.. moment -HTML5_FMT -TIME)])+ #?(:cljs (dayjs time-str+ #js ["HH:mm:ss.SSS"+ "HH:mm:ss"+ "HH:mm"]):clj (t/local-time time-str)))(defn- same?"True if these two datetimes are equivalent.- JVM objects are [[=]] but Moment.js values are not, so use the Moment.isSame method in CLJS."+ JVM objects are [[=]] but Day.js values are not, so use the Day.js isSame method in CLJS."[t1 t2]- #?(:cljs (.isSame ^moment/Moment t1 t2)+ #?(:cljs (.isSame ^dayjs t1 t2):clj (= t1 t2)))(defn- same-instant?"The same point on the timeline of the universe, adjusting to the same time zone (UTC)."[t1 t2]- #?(:cljs (.isSame ^moment/Moment t1 t2)+ #?(:cljs (.isSame ^dayjs t1 t2):clj (= (t/instant t1) (t/instant t2))))(def test-epoch@@ -192,7 +205,7 @@(is (same? (from-zulu exp-to) to) "end dates should be the same")))(defn- time-from [s]- #?(:cljs (moment s moment/HTML5_FMT.TIME_MS)+ #?(:cljs (dayjs s #js ["HH:mm:ss.SSS" "HH:mm:ss" "HH:mm"]):clj (t/local-time s)))(deftest coerce-to-time-test@@ -213,7 +226,7 @@"09:26:00.000" "09:26-08:00""19:26:00.000" "19:26-08:00"))- (testing "Moment and LocalTime values are simply returned"+ (testing "Day.js and LocalTime values are simply returned"(let [t (time-from "09:29")](is (= t (shared.ut/coerce-to-time t)))))@@ -454,7 +467,7 @@:hour "02:00"))(deftest ^:parallel zulu-add-datetime-test- #?(:cljs (moment-tz/tz.setDefault "Europe/Helsinki"))+ #?(:cljs (.tz.setDefault dayjs "Europe/Helsinki"))(testing "Datetime addition in string format works (#53724)"(try(doseq [datetime-fmt ["2024-01-01T00:00:00.000Z" "2024-01-01T00:00:00Z" "2024-01-01T00:00Z"]]@@ -470,11 +483,11 @@:quarter "2024-07-01T00:00Z":year "2026-01-01T00:00Z"))(finally- #?(:cljs (moment-tz/tz.setDefault))))))+ #?(:cljs (.tz.setDefault dayjs))))))(deftest ^:parallel zulu-add-time-test(testing "Time addition in string format works (#53724)"- #?(:cljs (moment-tz/tz.setDefault "Europe/Helsinki"))+ #?(:cljs (.tz.setDefault dayjs "Europe/Helsinki"))(try(doseq [time-fmt ["00:00:00.000Z" "00:00:00Z" "00:00Z"]](are [unit expected] (= expected@@ -484,7 +497,7 @@:minute "00:02Z":hour "02:00Z"))(finally- #?(:cljs (moment-tz/tz.setDefault))))))+ #?(:cljs (.tz.setDefault dayjs))))))(deftest ^:parallel extract-test(let [t (shared.ut/local-date-time 2024 12 06 10 20 30 500)]@@ -530,3 +543,22 @@"2020-04-18" (shared.ut/local-date 2020 4 18) :type/Date"2020-04-18" (shared.ut/local-date-time 2020 4 18 0 0 0) :type/Date"2020-04-18T15:25:18.500" (shared.ut/local-date-time 2020 4 18 15 25 18 500) :type/DateTime))++#?(:cljs+ (deftest ^:parallel dayjs-utc->local-date-test+ (testing "converts a dayjs UTC value to a JS Date preserving time values"+ (let [utc-dayjs (.utc dayjs "2024-11-28T10:20:30.123")+ result (shared.ut/dayjs-utc->local-date utc-dayjs)]+ (is (instance? js/Date result))+ ;; The JS Date should have the same year/month/day/hour/minute/second/millisecond+ ;; as the original UTC dayjs, but interpreted in local time+ (is (= 2024 (.getFullYear result)))+ (is (= 10 (.getMonth result))) ;; JS months are 0-indexed, so November = 10+ (is (= 28 (.getDate result)))+ (is (= 10 (.getHours result)))+ (is (= 20 (.getMinutes result)))+ (is (= 30 (.getSeconds result)))+ (is (= 123 (.getMilliseconds result)))))+ (testing "returns nil for invalid dayjs values"+ (is (nil? (shared.ut/dayjs-utc->local-date (dayjs "invalid-date"))))+ (is (nil? (shared.ut/dayjs-utc->local-date nil))))))