From 8e2499121331c0dbbeea897685ecfb1e1da989da Mon Sep 17 00:00:00 2001 From: Maciej Bodek Date: Mon, 23 Dec 2024 19:23:39 +0100 Subject: [PATCH] date validator --- packages/web-console/src/scenes/Editor/Metrics/utils.ts | 4 ++-- packages/web-console/src/utils/dateTime.ts | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/web-console/src/scenes/Editor/Metrics/utils.ts b/packages/web-console/src/scenes/Editor/Metrics/utils.ts index 7ca6fa81e..813bd1901 100644 --- a/packages/web-console/src/scenes/Editor/Metrics/utils.ts +++ b/packages/web-console/src/scenes/Editor/Metrics/utils.ts @@ -1,3 +1,4 @@ +import { isValidDate } from "./../../../utils/dateTime" import { format, formatISO, subMinutes } from "date-fns" import { utcToLocal } from "../../../utils/dateTime" import uPlot from "uplot" @@ -292,8 +293,7 @@ export const isDateToken = (token: string) => { // Converts tokens like `now-1h` or `now-7d` to date string export const durationTokenToDate = (token: string) => { - if (!isDateToken(token)) - return token.startsWith("now") ? "Invalid date" : token + if (!isDateToken(token)) return isValidDate(token) ? token : "Invalid date" const now = new Date() if (token === "now") return formatISO(now) const [_, _operator, value, unit] = token.match(/now(-)?(\d+)([a-z]+)$/)! diff --git a/packages/web-console/src/utils/dateTime.ts b/packages/web-console/src/utils/dateTime.ts index a5856123f..e62eb528c 100644 --- a/packages/web-console/src/utils/dateTime.ts +++ b/packages/web-console/src/utils/dateTime.ts @@ -1,6 +1,10 @@ import { format } from "date-fns" import { TZDate } from "@date-fns/tz" +export const isValidDate = (date: string): boolean => { + return !isNaN(Date.parse(date)) +} + export const getLocalTimeZone = () => { return Intl.DateTimeFormat().resolvedOptions().timeZone }