diff --git a/.changeset/time-picker-time-zone.md b/.changeset/time-picker-time-zone.md new file mode 100644 index 0000000000..c4800eb37d --- /dev/null +++ b/.changeset/time-picker-time-zone.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/app': patch +--- + +fix: Read and show time picker ranges in the display time zone, so applying a range with "Use UTC time" on no longer shifts it for users west of UTC diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index 8faba662ed..2a691b1703 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -238,8 +238,8 @@ import { useNewTimeQuery, } from './timeQuery'; import { useConfirm } from './useConfirm'; +import { useDisplayTimeZone } from './useDisplayTimeZone'; import { FormatTime } from './useFormatTime'; -import { useUserPreferences } from './useUserPreferences'; import { getMetricTableName, useLocalStorage } from './utils'; import { useZIndex, ZIndexContext } from './zIndex'; @@ -534,16 +534,14 @@ const Tile = ({ setHasBeenVisible(true); } - const { - userPreferences: { isUTC }, - } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); // Date range and granularity state local to the fullscreen view so that // changing them does not propagate up to the dashboard. const [fullscreenDateRange, setFullscreenDateRange] = useState<[Date, Date]>(dateRange); const [fullscreenInputValue, setFullscreenInputValue] = useState(() => - dateRangeToString(dateRange, isUTC), + dateRangeToString(dateRange, timeZone), ); const [fullscreenGranularity, setFullscreenGranularity] = useState< Granularity | 'auto' | undefined @@ -553,21 +551,21 @@ const Tile = ({ // Reinitialize to the dashboard's current date range and granularity // each time the fullscreen view is opened. setFullscreenDateRange(dateRange); - setFullscreenInputValue(dateRangeToString(dateRange, isUTC)); + setFullscreenInputValue(dateRangeToString(dateRange, timeZone)); setFullscreenGranularity( (granularity as Granularity | undefined) ?? 'auto', ); setIsFullscreen(true); - }, [dateRange, granularity, isUTC]); + }, [dateRange, granularity, timeZone]); const handleFullscreenSearch = useCallback( (value: string) => { - const [start, end] = parseTimeRangeInput(value, isUTC); + const [start, end] = parseTimeRangeInput(value, timeZone); if (start != null && end != null) { setFullscreenDateRange([start, end]); } }, - [isUTC], + [timeZone], ); useEffect(() => { @@ -1880,9 +1878,7 @@ function DBDashboardPage({ } = dashboardProps; const title = usePageTitle(dashboard?.name ? dashboard.name : 'Dashboard'); const confirm = useConfirm(); - const { - userPreferences: { isUTC }, - } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); const router = useRouter(); const dashboardId = router.query.dashboardId as string | undefined; @@ -2169,7 +2165,7 @@ function DBDashboardPage({ const currentRelativeDateRange = timeRangeInputToSeconds( displayedTimeInputValue, - isUTC, + timeZone, ); setDashboard( @@ -2202,7 +2198,7 @@ function DBDashboardPage({ getValues, filterValueEntries, onSubmit, - isUTC, + timeZone, displayedTimeInputValue, ]); const handleRemoveSavedQuery = useCallback(() => { @@ -3542,9 +3538,7 @@ function DBDashboardPageGuarded({ dashboardId: dashboardId as string | undefined, presetConfig, }); - const { - userPreferences: { isUTC }, - } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); const savedDateRange = dashboardProps.dashboard?.savedDateRange; // Keyed on the saved range, not the render: a relative range re-stringifies @@ -3557,8 +3551,8 @@ function DBDashboardPageGuarded({ ? parseRelativeTimeQuery(savedDateRange.value * 1000) : savedDateRange.value.map(v => new Date(v)); // TODO: show relative ranges as "Past Xh" via getRelativeInterval - return dateRangeToString([start, end], isUTC); - }, [savedDateRange, isUTC]); + return dateRangeToString([start, end], timeZone); + }, [savedDateRange, timeZone]); if (!dashboardProps || !router.isReady) return ; diff --git a/packages/app/src/__tests__/timeQuery.test.ts b/packages/app/src/__tests__/timeQuery.test.ts index b1788fc27b..38ec0ef881 100644 --- a/packages/app/src/__tests__/timeQuery.test.ts +++ b/packages/app/src/__tests__/timeQuery.test.ts @@ -17,7 +17,7 @@ describe('dateRangeToString', () => { expect( dateRangeToString( [new Date('2026-03-03T10:00:00'), new Date('2026-03-05T10:00:00')], - false, + undefined, ), ).toBe('Mar 3 10:00:00 - Mar 5 10:00:00'); }); @@ -26,16 +26,16 @@ describe('dateRangeToString', () => { expect( dateRangeToString( [new Date('2024-03-03T10:00:00'), new Date('2024-03-05T10:00:00')], - false, + undefined, ), ).toBe('Mar 3 2024 10:00:00 - Mar 5 2024 10:00:00'); }); - it('formats in UTC when isUTC is set', () => { + it('formats in the given time zone', () => { expect( dateRangeToString( [new Date('2024-12-31T23:00:00Z'), new Date('2025-01-01T01:00:00Z')], - true, + 'Etc/UTC', ), ).toBe('Dec 31 2024 23:00:00 - Jan 1 2025 01:00:00'); }); @@ -47,7 +47,7 @@ describe('dateRangeToString', () => { [new Date('2026-08-01T10:00:00'), new Date('2026-09-01T10:00:00')], ])('round-trips %s - %s through parseTimeRangeInput', (start, end) => { const [parsedStart, parsedEnd] = parseTimeRangeInput( - dateRangeToString([start, end], false), + dateRangeToString([start, end], undefined), ); expect(parsedStart).toEqual(start); expect(parsedEnd).toEqual(end); diff --git a/packages/app/src/components/TimePicker/TimePicker.tsx b/packages/app/src/components/TimePicker/TimePicker.tsx index 486643dea5..153963edff 100644 --- a/packages/app/src/components/TimePicker/TimePicker.tsx +++ b/packages/app/src/components/TimePicker/TimePicker.tsx @@ -25,6 +25,7 @@ import { DateInput, DateInputProps } from '@mantine/dates'; import { useDisclosure } from '@mantine/hooks'; import { IconBolt, IconCalendarFilled } from '@tabler/icons-react'; +import { useDisplayTimeZone } from '@/useDisplayTimeZone'; import { useUserPreferences } from '@/useUserPreferences'; import { TimePickerMode } from './types'; @@ -34,10 +35,12 @@ import { DURATION_OPTIONS, DURATIONS, formatTimeRangeText, + fromDateInputValue, LIVE_TAIL_DURATION_MS, LIVE_TAIL_TIME_QUERY, parseTimeRangeInput, RELATIVE_TIME_OPTIONS, + toDateInputValue, } from './utils'; const modeAtom = atomWithStorage( @@ -56,21 +59,31 @@ const toDate = (v: Date | string | null): Date | null => * Wrapper around Mantine v9 DateInput that bridges the Date ↔ string gap. * Mantine v9 DateInput expects/emits string values, but the TimePickerForm * stores Date objects (used by date-fns). This wrapper converts in both - * directions: value (Date → string) and onChange (string → Date). + * directions: value (Date → string) and onChange (string → Date), reading + * and writing the strings as clock times in `timeZone`. * * `withTime` is required: by default DateInput strips the time part and * normalizes values to midnight, even when `valueFormat` includes time * tokens. Setting `withTime` preserves HH:mm:ss so manually-typed times * survive blur/commit. */ -type DateInputCmpProps = Omit & { +type DateInputCmpProps = Omit< + DateInputProps, + 'value' | 'onChange' | 'minDate' | 'maxDate' +> & { value?: Date | null; onChange?: (value: Date | null) => void; + minDate?: Date | null; + maxDate?: Date; + timeZone: string | undefined; }; const DateInputCmp = ({ value, onChange: onChangeProp, + minDate, + maxDate, + timeZone, ...props }: DateInputCmpProps) => ( { + const date = dateParser(input, timeZone); + return date && toDateInputValue(date, timeZone); + }} onKeyDown={e => { if (e.key === 'Enter' && e.target instanceof HTMLInputElement) { e.target.blur(); } }} {...props} - value={value instanceof Date ? value.toISOString() : (value ?? null)} - onChange={v => onChangeProp?.(toDate(v))} + minDate={minDate ? toDateInputValue(minDate, timeZone) : undefined} + maxDate={maxDate ? toDateInputValue(maxDate, timeZone) : undefined} + value={value ? toDateInputValue(value, timeZone) : null} + onChange={v => onChangeProp?.(v ? fromDateInputValue(v, timeZone) : null)} /> ); @@ -124,6 +142,7 @@ const TimePickerComponent = ({ const { userPreferences: { timeFormat }, } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); const [opened, { close, toggle }] = useDisclosure(false); @@ -145,8 +164,8 @@ const TimePickerComponent = ({ const form = useTimePickerForm({ mode }); const dateRange = React.useMemo(() => { - return parseTimeRangeInput(value); - }, [value]); + return parseTimeRangeInput(value, timeZone); + }, [value, timeZone]); React.useEffect(() => { // Only update form values from external dateRange when popover is closed @@ -191,12 +210,15 @@ const TimePickerComponent = ({ if (!from || !to) { return; } - const rangeStr = formatTimeRangeText([from, to], { clock: timeFormat }); + const rangeStr = formatTimeRangeText([from, to], { + timeZone, + clock: timeFormat, + }); onChange(rangeStr); onSearch(rangeStr); close(); }, - [close, onChange, onSearch, timeFormat], + [close, onChange, onSearch, timeFormat, timeZone], ); const handleApply = React.useCallback(() => { @@ -468,6 +490,7 @@ const TimePickerComponent = ({ <> Start time End time @@ -487,6 +511,7 @@ const TimePickerComponent = ({ <> Time ({ + useDisplayTimeZone: () => mockTimeZone, +})); + +// Tests run with TZ=America/New_York, behind UTC, where a UTC range ending +// now used to be read as local time, land in the future, and get clamped. +describe('TimePicker time zone', () => { + const LAST_HOUR_UTC = 'Oct 22 14:00:00 - Oct 22 15:00:00'; + + beforeEach(() => { + // Only fake the clock: Mantine's popover relies on real timers. + jest.useFakeTimers({ + now: new Date('2026-10-22T15:00:00Z'), + doNotFake: [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'setImmediate', + 'clearImmediate', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'queueMicrotask', + 'nextTick', + ], + }); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + function renderPicker(timeZone: string | undefined, inputValue: string) { + mockTimeZone = timeZone; + const onSearch = jest.fn(); + renderWithMantine( + , + ); + fireEvent.click(screen.getByTestId('time-picker-input')); + return { onSearch }; + } + + it('shows and applies the range in the display time zone', async () => { + const { onSearch } = renderPicker('Etc/UTC', LAST_HOUR_UTC); + + expect( + await screen.findAllByDisplayValue('2026-10-22 14:00:00'), + ).not.toHaveLength(0); + expect(screen.getAllByDisplayValue('2026-10-22 15:00:00')).not.toHaveLength( + 0, + ); + + fireEvent.click(screen.getByTestId('time-picker-apply')); + expect(onSearch).toHaveBeenCalledWith( + 'Oct 22 2:00:00 PM - Oct 22 3:00:00 PM', + ); + }); + + it('shows the range in the local zone without a display time zone', async () => { + renderPicker(undefined, 'Oct 22 10:00:00 - Oct 22 11:00:00'); + + expect( + await screen.findAllByDisplayValue('2026-10-22 10:00:00'), + ).not.toHaveLength(0); + expect(screen.getAllByDisplayValue('2026-10-22 11:00:00')).not.toHaveLength( + 0, + ); + }); +}); diff --git a/packages/app/src/components/TimePicker/__tests__/utils.test.ts b/packages/app/src/components/TimePicker/__tests__/utils.test.ts index 4fc7a286f5..bf94ab774e 100644 --- a/packages/app/src/components/TimePicker/__tests__/utils.test.ts +++ b/packages/app/src/components/TimePicker/__tests__/utils.test.ts @@ -1,9 +1,11 @@ import { dateParser, formatTimeRangeText, + fromDateInputValue, parseTimeRangeInput, rangeNeedsExplicitYear, timeRangeInputToSeconds, + toDateInputValue, } from '@/components/TimePicker/utils'; describe('dateParser', () => { @@ -198,14 +200,15 @@ describe('rangeNeedsExplicitYear', () => { ).toBe(true); }); - it('compares years in UTC when isUTC is set', () => { + it('compares years in the given time zone', () => { jest.setSystemTime(new Date('2025-06-15T12:00:00Z')); - expect( - rangeNeedsExplicitYear( - [new Date('2024-12-31T23:00:00Z'), new Date('2025-01-01T01:00:00Z')], - true, - ), - ).toBe(true); + const range: [Date, Date] = [ + new Date('2024-12-31T23:00:00Z'), + new Date('2025-01-01T01:00:00Z'), + ]; + expect(rangeNeedsExplicitYear(range, 'Etc/UTC')).toBe(true); + // Already Jan 1 2025 in Tokyo for both dates. + expect(rangeNeedsExplicitYear(range, 'Asia/Tokyo')).toBe(false); }); }); @@ -275,18 +278,119 @@ describe('timeRangeInputToSeconds', () => { }); it('returns the relative range length in seconds', () => { - expect(timeRangeInputToSeconds('Past 1h', false)).toBe(3600); - expect(timeRangeInputToSeconds('Past 15m', false)).toBe(900); + expect(timeRangeInputToSeconds('Past 1h')).toBe(3600); + expect(timeRangeInputToSeconds('Past 15m')).toBe(900); }); it('returns the span of an absolute range', () => { - expect(timeRangeInputToSeconds('2024-01-15 to 2024-01-16', false)).toBe( - 86400, - ); + expect(timeRangeInputToSeconds('2024-01-15 to 2024-01-16')).toBe(86400); }); it('returns null for unparseable input', () => { - expect(timeRangeInputToSeconds('', false)).toBeNull(); - expect(timeRangeInputToSeconds('not a date', false)).toBeNull(); + expect(timeRangeInputToSeconds('')).toBeNull(); + expect(timeRangeInputToSeconds('not a date')).toBeNull(); + }); +}); + +describe('time zones', () => { + beforeEach(() => { + jest.useFakeTimers(); + jest.setSystemTime(new Date('2026-10-22T15:00:00Z')); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('reads a range ending now in the given zone without clamping it', () => { + const lastHour = [ + new Date('2026-10-22T14:00:00Z'), + new Date('2026-10-22T15:00:00Z'), + ]; + expect( + parseTimeRangeInput('Oct 22 14:00:00 - Oct 22 15:00:00', 'Etc/UTC'), + ).toEqual(lastHour); + expect( + parseTimeRangeInput( + 'Oct 22 07:00:00 - Oct 22 08:00:00', + 'America/Los_Angeles', + ), + ).toEqual(lastHour); + }); + + it.each(['Etc/UTC', 'Asia/Tokyo', 'America/Los_Angeles'])( + 'round-trips a range across a DST change in %s', + timeZone => { + jest.setSystemTime(new Date('2026-11-10T12:00:00Z')); + const range: [Date, Date] = [ + new Date('2026-10-31T15:00:00Z'), + new Date('2026-11-02T16:00:00Z'), + ]; + for (const clock of ['12h', '24h'] as const) { + expect( + parseTimeRangeInput( + formatTimeRangeText(range, { timeZone, clock }), + timeZone, + ), + ).toEqual(range); + } + }, + ); + + it('resolves relative words against the date in the given zone', () => { + // Oct 22 12:00 in Tokyo, Oct 21 20:00 in Los Angeles. + jest.setSystemTime(new Date('2026-10-22T03:00:00Z')); + expect(parseTimeRangeInput('yesterday 5pm', 'Asia/Tokyo')[0]).toEqual( + new Date('2026-10-21T08:00:00Z'), + ); + expect( + parseTimeRangeInput('yesterday 5pm', 'America/Los_Angeles')[0], + ).toEqual(new Date('2026-10-21T00:00:00Z')); + }); + + it('keeps an explicit offset in the text', () => { + expect( + parseTimeRangeInput('2026-10-22T10:00:00Z', 'America/Los_Angeles')[0], + ).toEqual(new Date('2026-10-22T10:00:00Z')); + }); + + // New York repeats 01:00-02:00 on Nov 1 2026: first at UTC-4, then at UTC-5. + it('keeps both occurrences of the repeated hour apart', () => { + jest.setSystemTime(new Date('2026-11-01T12:00:00Z')); + const zone = 'America/New_York'; + expect(parseTimeRangeInput('2026-11-01T01:30:00-04:00', zone)[0]).toEqual( + new Date('2026-11-01T05:30:00Z'), + ); + expect(parseTimeRangeInput('2026-11-01T01:30:00-05:00', zone)[0]).toEqual( + new Date('2026-11-01T06:30:00Z'), + ); + }); + + it('ends a relative range at now during the repeated hour', () => { + jest.setSystemTime(new Date('2026-11-01T06:30:00Z')); + expect(parseTimeRangeInput('Past 1h', 'America/New_York')).toEqual([ + new Date('2026-11-01T05:30:00Z'), + new Date('2026-11-01T06:30:00Z'), + ]); + }); + + it('parses date input text in the given zone', () => { + expect(dateParser('Oct 22 07:00', 'America/Los_Angeles')).toEqual( + new Date('2026-10-22T14:00:00Z'), + ); + }); + + it('converts DateInput values in the given zone', () => { + const date = new Date('2026-10-22T15:00:00Z'); + expect(toDateInputValue(date, 'America/Los_Angeles')).toBe( + '2026-10-22 08:00:00', + ); + expect( + fromDateInputValue('2026-10-22 08:00:00', 'America/Los_Angeles'), + ).toEqual(date); + expect(fromDateInputValue('2026-10-22', 'Etc/UTC')).toEqual( + new Date('2026-10-22T00:00:00Z'), + ); + expect(fromDateInputValue('not a date', 'Etc/UTC')).toBeNull(); }); }); diff --git a/packages/app/src/components/TimePicker/utils.ts b/packages/app/src/components/TimePicker/utils.ts index e5628ffec5..b64a14e5f1 100644 --- a/packages/app/src/components/TimePicker/utils.ts +++ b/packages/app/src/components/TimePicker/utils.ts @@ -1,19 +1,69 @@ import * as chrono from 'chrono-node'; import ms from 'ms'; -import { formatDate } from '@hyperdx/common-utils/dist/core/utils'; +import { + formatDate, + fromWallClock, + toWallClock, +} from '@hyperdx/common-utils/dist/core/utils'; function currentDate(): Date { // eslint-disable-next-line no-restricted-syntax return new Date(); } -function normalizeParsedDate(parsed?: chrono.ParsedComponents): Date | null { +function resolveTimeZone(timeZone?: string): string { + return timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone; +} + +// chrono reads text in one fixed offset. Using the zone's current offset makes +// words like "yesterday" resolve against today's date in that zone. +function chronoReference(timeZone: string): chrono.ParsingReference { + const now = currentDate(); + const offsetMs = toWallClock(now, timeZone).getTime() - now.getTime(); + return { instant: now, timezone: offsetMs / 60_000 }; +} + +// The parsed date as a wall-clock date (see toWallClock). Readings without an +// offset are rebuilt from their fields instead of using chrono's fixed offset, +// so dates on the other side of a DST change get their own offset. +function parsedWallClock( + parsed: chrono.ParsedComponents, + timeZone: string, +): Date { + if (parsed.isCertain('timezoneOffset')) { + // An offset in the text ("10:00Z") or a time relative to now ("1h ago"). + return toWallClock(parsed.date(), timeZone); + } + return new Date( + Date.UTC( + parsed.get('year') ?? 0, + (parsed.get('month') ?? 1) - 1, + parsed.get('day') ?? 1, + parsed.get('hour') ?? 0, + parsed.get('minute') ?? 0, + parsed.get('second') ?? 0, + parsed.get('millisecond') ?? 0, + ), + ); +} + +// Compares wall-clock dates so the checks against "now" happen in the requested +// zone, but returns an instant. Instants that are already known (now, or text +// with an offset) are returned as-is: a clock reading in the hour repeated when +// clocks go back can't say which occurrence it is. +function normalizeParsedDate( + parsed: chrono.ParsedComponents | undefined, + timeZone: string, +): Date | null { if (!parsed) { return null; } - const now = currentDate(); - const parsedDate = parsed.date(); + const nowInstant = currentDate(); + const now = toWallClock(nowInstant, timeZone); + const parsedDate = parsedWallClock(parsed, timeZone); + let isExactNow = true; + let isExactParsed = parsed.isCertain('timezoneOffset'); // If all of the time components have been inferred, set the time components of now // to match the parsed time components. This ensures that the comparison later on uses @@ -26,10 +76,13 @@ function normalizeParsedDate(parsed?: chrono.ParsedComponents): Date | null { parsed.isCertain('millisecond') ) ) { - now.setHours(parsed.get('hour') || 0); - now.setMinutes(parsed.get('minute') || 0); - now.setSeconds(parsed.get('second') || 0); - now.setMilliseconds(parsed.get('millisecond') || 0); + now.setUTCHours( + parsed.get('hour') || 0, + parsed.get('minute') || 0, + parsed.get('second') || 0, + parsed.get('millisecond') || 0, + ); + isExactNow = false; } // Handle future dates: @@ -40,21 +93,24 @@ function normalizeParsedDate(parsed?: chrono.ParsedComponents): Date | null { const oneDayFromNow = now.getTime() + ms('1d'); if (parsedDate.getTime() <= oneDayFromNow) { // Slightly in the future: clamp to now - return now; + return isExactNow ? nowInstant : fromWallClock(now, timeZone); } else if (!parsed.isCertain('year')) { // Significantly in the future with inferred year: shift year back - parsedDate.setFullYear(parsedDate.getFullYear() - 1); + parsedDate.setUTCFullYear(parsedDate.getUTCFullYear() - 1); + isExactParsed = false; } } - return parsedDate; + return isExactParsed ? parsed.date() : fromWallClock(parsedDate, timeZone); } +// `timeZone` is an IANA name the text is read in; the local zone if omitted. export function parseTimeRangeInput( str: string, - isUTC: boolean = false, + timeZone?: string, ): [Date | null, Date | null] { - const parsedTimeResults = chrono.parse(str, isUTC ? { timezone: 0 } : {}); + const zone = resolveTimeZone(timeZone); + const parsedTimeResults = chrono.parse(str, chronoReference(zone)); if (parsedTimeResults.length === 0) { return [null, null]; } @@ -63,9 +119,9 @@ export function parseTimeRangeInput( parsedTimeResults.length === 1 ? parsedTimeResults[0] : parsedTimeResults[1]; - const start = normalizeParsedDate(parsedTimeResult.start); - const end = normalizeParsedDate(parsedTimeResult.end) || currentDate(); - if (end && start && end < start) { + const start = normalizeParsedDate(parsedTimeResult.start, zone); + const end = normalizeParsedDate(parsedTimeResult.end, zone) ?? currentDate(); + if (start && end < start) { // For date range strings that omit years, the chrono parser will infer the year // using the current year. This can cause the start date to be in the future, and // returned as the end date instead of the start date. After normalizing the dates, @@ -81,10 +137,11 @@ export function parseTimeRangeInput( // current year survive that, so every other range needs an explicit year. export function rangeNeedsExplicitYear( range: readonly [Date, Date], - isUTC: boolean = false, + timeZone?: string, ): boolean { + const zone = resolveTimeZone(timeZone); const now = currentDate(); - const getYear = (d: Date) => (isUTC ? d.getUTCFullYear() : d.getFullYear()); + const getYear = (d: Date) => toWallClock(d, zone).getUTCFullYear(); return range.some(d => getYear(d) !== getYear(now) || d > now); } @@ -93,20 +150,22 @@ export function rangeNeedsExplicitYear( export function formatTimeRangeText( range: readonly [Date, Date], { - isUTC = false, + timeZone, clock = '24h', - }: { isUTC?: boolean; clock?: '12h' | '24h' } = {}, + }: { timeZone?: string; clock?: '12h' | '24h' } = {}, ): string { - const format = rangeNeedsExplicitYear(range, isUTC) ? 'withYear' : 'normal'; - return range.map(d => formatDate(d, { isUTC, format, clock })).join(' - '); + const format = rangeNeedsExplicitYear(range, timeZone) + ? 'withYear' + : 'normal'; + return range.map(d => formatDate(d, { timeZone, format, clock })).join(' - '); } // Duration of a time range input in seconds, or null if it doesn't parse. export function timeRangeInputToSeconds( str: string, - isUTC: boolean, + timeZone?: string, ): number | null { - const [start, end] = parseTimeRangeInput(str, isUTC); + const [start, end] = parseTimeRangeInput(str, timeZone); if (start == null || end == null) return null; return (end.getTime() - start.getTime()) / 1000; } @@ -173,10 +232,31 @@ export const DURATIONS: Record = { '12h': { hours: 12 }, }; -export const dateParser = (input?: string) => { +export const dateParser = (input?: string, timeZone?: string) => { if (!input) { return null; } - const parsed = chrono.casual.parse(input)[0]; - return normalizeParsedDate(parsed?.start); + const zone = resolveTimeZone(timeZone); + const parsed = chrono.casual.parse(input, chronoReference(zone))[0]; + return normalizeParsedDate(parsed?.start, zone); }; + +// Mantine DateInput values are clock readings like "2026-10-22 13:05:00", +// which the picker shows in `timeZone` rather than the local zone. +export function toDateInputValue(date: Date, timeZone?: string): string { + return toWallClock(date, resolveTimeZone(timeZone)) + .toISOString() + .slice(0, 19) + .replace('T', ' '); +} + +export function fromDateInputValue( + value: string, + timeZone?: string, +): Date | null { + const [date, time = '00:00:00'] = value.split(' '); + const wallClock = new Date(`${date}T${time}Z`); + return Number.isNaN(wallClock.getTime()) + ? null + : fromWallClock(wallClock, resolveTimeZone(timeZone)); +} diff --git a/packages/app/src/timeQuery.ts b/packages/app/src/timeQuery.ts index 8a33845e0d..d13f525768 100644 --- a/packages/app/src/timeQuery.ts +++ b/packages/app/src/timeQuery.ts @@ -28,14 +28,16 @@ import { formatTimeRangeText, parseTimeRangeInput, } from './components/TimePicker/utils'; -import { useUserPreferences } from './useUserPreferences'; +import { useDisplayTimeZone } from './useDisplayTimeZone'; import { usePrevious } from './utils'; const LIVE_TAIL_TIME_QUERY = 'Live Tail'; const LIVE_TAIL_REFRESH_INTERVAL_MS = 1000; -export const dateRangeToString = (range: [Date, Date], isUTC: boolean) => - formatTimeRangeText(range, { isUTC, clock: '24h' }); +export const dateRangeToString = ( + range: [Date, Date], + timeZone: string | undefined, +) => formatTimeRangeText(range, { timeZone, clock: '24h' }); function isInputTimeQueryLive(inputTimeQuery: string) { return inputTimeQuery === '' || inputTimeQuery.includes(LIVE_TAIL_TIME_QUERY); @@ -49,16 +51,16 @@ export function parseRelativeTimeQuery(interval: number): [Date, Date] { function parseTimeQuery( timeQuery: string, - isUTC: boolean, + timeZone: string | undefined, ): [Date | null, Date | null] { - return parseTimeRangeInput(timeQuery, isUTC); + return parseTimeRangeInput(timeQuery, timeZone); } function parseValidTimeRange( timeQuery: string, - isUTC: boolean, + timeZone: string | undefined, ): [Date, Date] | undefined { - const [start, end] = parseTimeQuery(timeQuery, isUTC); + const [start, end] = parseTimeQuery(timeQuery, timeZone); if (start != null && end != null) { return [start, end]; } @@ -79,9 +81,7 @@ export function useTimeQuery({ const isReady = typeof window === 'undefined' ? true : router.isReady; const prevIsReady = usePrevious(isReady); - const { - userPreferences: { isUTC }, - } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); const [displayedTimeInputValue, setDisplayedTimeInputValue] = useState< undefined | string @@ -118,7 +118,7 @@ export function useTimeQuery({ // If we're missing the time range query, let's parse it from the input time query const timeQueryDerivedInputValue = dateRangeToString( [new Date(_timeRangeQuery.from), new Date(_timeRangeQuery.to)], - isUTC, + timeZone, ); setDisplayedTimeInputValue(timeQueryDerivedInputValue); setInputTimeQuery(timeQueryDerivedInputValue); @@ -131,7 +131,7 @@ export function useTimeQuery({ defaultValue, inputTimeQuery, isReady, - isUTC, + timeZone, prevIsReady, setInputTimeQuery, setDisplayedTimeInputValue, @@ -154,7 +154,7 @@ export function useTimeQuery({ isReady && timeRangeQuery.from != -1 && timeRangeQuery.to != -1 ? dateRangeToString( [new Date(timeRangeQuery.from), new Date(timeRangeQuery.to)], - isUTC, + timeZone, ) : undefined; @@ -172,7 +172,7 @@ export function useTimeQuery({ !isInputTimeQueryLive(inputTimeQuery) && prevInputTimeQuery != inputTimeQuery ) { - const timeRange = parseValidTimeRange(inputTimeQuery, isUTC); + const timeRange = parseValidTimeRange(inputTimeQuery, timeZone); inputTimeQueryDerivedTimeQueryRef.current = timeRange; if ( @@ -189,7 +189,7 @@ export function useTimeQuery({ }, [ isReady, inputTimeQuery, - isUTC, + timeZone, _timeRangeQuery, setTimeRangeQuery, prevInputTimeQuery, @@ -313,7 +313,7 @@ export function useTimeQuery({ setTempLiveTailTimeRange(liveTailTimeRange); setTimeRangeQuery({ from: start.getTime(), to: end.getTime() }); setLiveTailTimeRange(undefined); - const dateRangeStr = dateRangeToString([start, end], isUTC); + const dateRangeStr = dateRangeToString([start, end], timeZone); setDisplayedTimeInputValue(dateRangeStr); setInputTimeQuery(dateRangeStr); } @@ -323,7 +323,7 @@ export function useTimeQuery({ setTimeRangeQuery, setDisplayedTimeInputValue, liveTailTimeRange, - isUTC, + timeZone, setInputTimeQuery, ], ); @@ -338,12 +338,12 @@ export function useTimeQuery({ searchedTimeRange, onSearch: useCallback( (timeQuery: string) => { - const [start, end] = parseTimeQuery(timeQuery, isUTC); + const [start, end] = parseTimeQuery(timeQuery, timeZone); // TODO: Add validation UI if (start != null && end != null) { setTimeRangeQuery({ from: start.getTime(), to: end.getTime() }); if (timeQuery.toLowerCase().indexOf('past') === -1) { - const dateRangeStr = dateRangeToString([start, end], isUTC); + const dateRangeStr = dateRangeToString([start, end], timeZone); setDisplayedTimeInputValue(dateRangeStr); setInputTimeQuery(dateRangeStr); } else { @@ -351,16 +351,26 @@ export function useTimeQuery({ } } }, - [isUTC, setTimeRangeQuery, setDisplayedTimeInputValue, setInputTimeQuery], + [ + timeZone, + setTimeRangeQuery, + setDisplayedTimeInputValue, + setInputTimeQuery, + ], ), onTimeRangeSelect: useCallback( (start: Date, end: Date) => { setTimeRangeQuery({ from: start.getTime(), to: end.getTime() }); - const dateRangeStr = dateRangeToString([start, end], isUTC); + const dateRangeStr = dateRangeToString([start, end], timeZone); setDisplayedTimeInputValue(dateRangeStr); setInputTimeQuery(dateRangeStr); }, - [isUTC, setTimeRangeQuery, setDisplayedTimeInputValue, setInputTimeQuery], + [ + timeZone, + setTimeRangeQuery, + setDisplayedTimeInputValue, + setInputTimeQuery, + ], ), setIsLive, }; @@ -418,15 +428,13 @@ export function useNewTimeQuery({ // We need to return true in SSR to prevent mismatch issues const isReady = typeof window === 'undefined' ? true : router.isReady; - const { - userPreferences: { isUTC }, - } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); const [ deprecatedDisplayedTimeInputValue, deprecatedSetDisplayedTimeInputValue, ] = useState(() => { - return initialDisplayValue ?? dateRangeToString(initialTimeRange, isUTC); + return initialDisplayValue ?? dateRangeToString(initialTimeRange, timeZone); }); const _setDisplayedTimeInputValue = @@ -447,13 +455,13 @@ export function useNewTimeQuery({ const onSearch = useCallback( (timeQuery: string) => { - const [start, end] = parseTimeQuery(timeQuery, isUTC); + const [start, end] = parseTimeQuery(timeQuery, timeZone); // TODO: Add validation UI if (start != null && end != null) { setTimeRangeQuery({ from: start.getTime(), to: end.getTime() }); } }, - [isUTC, setTimeRangeQuery], + [timeZone, setTimeRangeQuery], ); useEffect(() => { @@ -465,14 +473,14 @@ export function useNewTimeQuery({ const relativeInterval = showRelativeInterval && getRelativeInterval(start, end); const dateRangeStr = - relativeInterval || dateRangeToString([start, end], isUTC); + relativeInterval || dateRangeToString([start, end], timeZone); if (updateInput !== false) { _setDisplayedTimeInputValue(dateRangeStr); } } } else if (from == null && to == null && isReady) { setSearchedTimeRange(initialTimeRange); - const dateRangeStr = dateRangeToString(initialTimeRange, isUTC); + const dateRangeStr = dateRangeToString(initialTimeRange, timeZone); if (updateInput !== false) { if (!showRelativeInterval) { _setDisplayedTimeInputValue(dateRangeStr); @@ -483,7 +491,7 @@ export function useNewTimeQuery({ } }, [ isReady, - isUTC, + timeZone, from, to, initialDisplayValue, @@ -505,19 +513,22 @@ export function useNewTimeQuery({ (start: Date, end: Date, displayedTimeInputValue?: string | null) => { setTimeRangeQuery({ from: start.getTime(), to: end.getTime() }); setSearchedTimeRange([start, end]); - const dateRangeStr = dateRangeToString([start, end], isUTC); + const dateRangeStr = dateRangeToString([start, end], timeZone); if (displayedTimeInputValue !== null) { _setDisplayedTimeInputValue(displayedTimeInputValue ?? dateRangeStr); } }, - [setTimeRangeQuery, isUTC, _setDisplayedTimeInputValue], + [setTimeRangeQuery, timeZone, _setDisplayedTimeInputValue], ), }; } -function getRangeOrFallback(query: string, isUTC: boolean): [Date, Date] { +function getRangeOrFallback( + query: string, + timeZone: string | undefined, +): [Date, Date] { return ( - parseValidTimeRange(query, isUTC) ?? + parseValidTimeRange(query, timeZone) ?? // This fallback catches arbitrary inputs but shouldn't be reachable // for standard literal labels (e.g., 'Past 1h') since they are always valid. parseRelativeTimeQuery(60 * 60 * 1000) @@ -525,20 +536,18 @@ function getRangeOrFallback(query: string, isUTC: boolean): [Date, Date] { } export function useDefaultTimeRange(query: string): [Date, Date] { - const { - userPreferences: { isUTC }, - } = useUserPreferences(); + const timeZone = useDisplayTimeZone(); const [state, setState] = useState<{ query: string; range: [Date, Date] }>( () => ({ query, - range: getRangeOrFallback(query, isUTC), + range: getRangeOrFallback(query, timeZone), }), ); if (state.query !== query) { const newState = { query, - range: getRangeOrFallback(query, isUTC), + range: getRangeOrFallback(query, timeZone), }; setState(newState); return newState.range; diff --git a/packages/app/src/useDisplayTimeZone.ts b/packages/app/src/useDisplayTimeZone.ts new file mode 100644 index 0000000000..fd830a811c --- /dev/null +++ b/packages/app/src/useDisplayTimeZone.ts @@ -0,0 +1,14 @@ +import { UTC_TIME_ZONE } from '@hyperdx/common-utils/dist/core/utils'; + +import { useUserPreferences } from './useUserPreferences'; + +/** + * IANA time zone that times are shown and typed in, or undefined for the + * local zone. + */ +export function useDisplayTimeZone(): string | undefined { + const { + userPreferences: { isUTC }, + } = useUserPreferences(); + return isUTC ? UTC_TIME_ZONE : undefined; +} diff --git a/packages/common-utils/src/__tests__/utils.test.ts b/packages/common-utils/src/__tests__/utils.test.ts index fca664ed9a..05842a0e10 100644 --- a/packages/common-utils/src/__tests__/utils.test.ts +++ b/packages/common-utils/src/__tests__/utils.test.ts @@ -10,6 +10,7 @@ import { extractSettingsClauseFromEnd, findJsonExpressions, formatDate, + fromWallClock, getAlignedDateRange, getDistributedTableArgs, getFirstOrderingItem, @@ -29,6 +30,7 @@ import { resolvePercentileAggFn, splitAndTrimCSV, splitAndTrimWithBracket, + toWallClock, } from '@/core/utils'; import { isBuilderSavedChartConfig } from '@/guards'; import { @@ -94,6 +96,73 @@ describe('utils', () => { }), ).toEqual('Jan 1 12:00:00.000'); }); + + it('formats in the given time zone', () => { + const date = new Date('2021-01-01T12:00:00Z'); + expect( + formatDate(date, { clock: '24h', timeZone: 'Asia/Tokyo' }), + ).toEqual('Jan 1 21:00:00'); + }); + + it('prefers timeZone over isUTC', () => { + const date = new Date('2021-01-01T12:00:00Z'); + expect( + formatDate(date, { + clock: '24h', + isUTC: true, + timeZone: 'America/Los_Angeles', + }), + ).toEqual('Jan 1 04:00:00'); + }); + }); + + describe('toWallClock / fromWallClock', () => { + it('reads the clock in the given zone into UTC fields', () => { + expect( + toWallClock( + new Date('2026-10-22T15:00:00Z'), + 'America/Los_Angeles', + ).toISOString(), + ).toBe('2026-10-22T08:00:00.000Z'); + }); + + it('uses the offset in effect on each side of a DST change', () => { + // Los Angeles leaves daylight time (UTC-7) for standard time (UTC-8) on Nov 1 2026. + expect( + fromWallClock( + new Date('2026-10-31T08:00:00Z'), + 'America/Los_Angeles', + ).toISOString(), + ).toBe('2026-10-31T15:00:00.000Z'); + expect( + fromWallClock( + new Date('2026-11-02T08:00:00Z'), + 'America/Los_Angeles', + ).toISOString(), + ).toBe('2026-11-02T16:00:00.000Z'); + }); + + it('reads the clock correctly in the hours around a DST change', () => { + // New York goes from UTC-4 to UTC-5 at 06:00 UTC on Nov 1 2026. + const read = (iso: string) => + toWallClock(new Date(iso), 'America/New_York').toISOString(); + expect(read('2026-11-01T03:30:00Z')).toBe('2026-10-31T23:30:00.000Z'); + expect(read('2026-11-01T05:30:00Z')).toBe('2026-11-01T01:30:00.000Z'); + expect(read('2026-11-01T06:30:00Z')).toBe('2026-11-01T01:30:00.000Z'); + // And from UTC-5 to UTC-4 at 07:00 UTC on Mar 8 2026. + expect(read('2026-03-08T06:30:00Z')).toBe('2026-03-08T01:30:00.000Z'); + expect(read('2026-03-08T07:30:00Z')).toBe('2026-03-08T03:30:00.000Z'); + }); + + it.each(['Etc/UTC', 'Asia/Kolkata', 'America/Los_Angeles'])( + 'round-trips through %s', + timeZone => { + const date = new Date('2026-03-08T10:30:15.250Z'); + expect(fromWallClock(toWallClock(date, timeZone), timeZone)).toEqual( + date, + ); + }, + ); }); describe('splitAndTrimCSV', () => { diff --git a/packages/common-utils/src/core/utils.ts b/packages/common-utils/src/core/utils.ts index e249239c9c..3fba09931b 100644 --- a/packages/common-utils/src/core/utils.ts +++ b/packages/common-utils/src/core/utils.ts @@ -1,6 +1,6 @@ // Port from ChartUtils + source.ts import { add as fnsAdd, format as fnsFormat } from 'date-fns'; -import { formatInTimeZone } from 'date-fns-tz'; +import { formatInTimeZone, zonedTimeToUtc } from 'date-fns-tz'; import { omit } from 'lodash'; import { z } from 'zod'; @@ -760,25 +760,56 @@ const TIME_TOKENS = { }, }; +export const UTC_TIME_ZONE = 'Etc/UTC'; + +/** + * Formats `date` in `timeZone` (an IANA name). `isUTC` is shorthand for + * `timeZone: UTC_TIME_ZONE`; with neither set, the local zone is used. + */ export const formatDate = ( date: Date, { isUTC = false, + timeZone, format = 'normal', clock = '12h', }: { isUTC?: boolean; + timeZone?: string; format?: 'normal' | 'short' | 'withMs' | 'time' | 'withYear'; clock?: '12h' | '24h'; }, ) => { const formatStr = TIME_TOKENS[format][clock]; + const zone = timeZone ?? (isUTC ? UTC_TIME_ZONE : undefined); - return isUTC - ? formatInTimeZone(date, 'Etc/UTC', formatStr) + return zone + ? formatInTimeZone(date, zone, formatStr) : fnsFormat(date, formatStr); }; +/** + * The clock reading of `date` in `timeZone`, as a Date whose UTC fields hold + * that reading. Lets date maths and parsing run in a zone other than the + * runtime's own, using the UTC getters and setters. + */ +export function toWallClock(date: Date, timeZone: string): Date { + // Not getTimezoneOffset: it takes a clock reading, so for instants near a + // DST change it returns the offset from the other side of the change. + return new Date( + formatInTimeZone(date, timeZone, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"), + ); +} + +/** + * Inverse of `toWallClock`, using the zone's offset on that date. A reading in + * the hour repeated when clocks go back maps to its first occurrence. + */ +export function fromWallClock(wallClock: Date, timeZone: string): Date { + // An ISO string without an offset is read as a clock reading in `timeZone`. + return zonedTimeToUtc(wallClock.toISOString().slice(0, 23), timeZone); +} + type Dashboard = z.infer; type DashboardTemplate = z.infer; type TileTemplate = z.infer;