Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(insights): use timezone-safe date parsing to prevent calendar day shifts (#57593)

Thomas Obermüller56f9a3fe94cb
diff --git a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
index 955861b40665..099f96c82b29 100644
--- a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
+++ b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts
@@ -2,9 +2,10 @@ import { actions, connect, kea, key, listeners, path, props, reducers, selectors
import { isPersonPropertyFilter, parseProperties } from 'lib/components/PropertyFilters/utils'
import { FEATURE_FLAGS } from 'lib/constants'
-import { Dayjs, dayjs, dayjsLocalToTimezone } from 'lib/dayjs'
+import { Dayjs, dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { groupBy } from 'lib/utils'
+import { parseDateInTimezone } from 'lib/utils/dateTimeUtils'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -136,7 +137,7 @@ export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
tickDates: [
(s) => [s.timezone, (_, props: AnnotationsOverlayLogicProps) => props.dates, s.tickPositions],
(timezone, dates, tickPositions): Dayjs[] =>
- tickPositions.map((dateIndex) => dayjsLocalToTimezone(dates[dateIndex], timezone)),
+ tickPositions.map((dateIndex) => parseDateInTimezone(dates[dateIndex], timezone)),
],
dateRange: [
(s) => [s.timezone, (_, props: AnnotationsOverlayLogicProps) => props.dates, s.intervalUnit],
@@ -144,8 +145,8 @@ export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
if (dates.length === 0) {
return null
}
- const first = dayjsLocalToTimezone(dates[0], timezone)
- const last = dayjsLocalToTimezone(dates[dates.length - 1], timezone).add(1, intervalUnit)
+ const first = parseDateInTimezone(dates[0], timezone)
+ const last = parseDateInTimezone(dates[dates.length - 1], timezone).add(1, intervalUnit)
return [first, last]
},
],
@@ -207,7 +208,7 @@ export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
const incidentDates = ['2026-01-06', '2026-01-07']
const specialAnnotations: DatedAnnotationType[] = incidentDates
.map((dateStr, index) => {
- const dateInTimezone = dayjsLocalToTimezone(dateStr, timezone).startOf('day')
+ const dateInTimezone = parseDateInTimezone(dateStr, timezone).startOf('day')
// Only include if date is within the date range
if (dateInTimezone >= dateRange[0] && dateInTimezone < dateRange[1]) {
@@ -263,7 +264,7 @@ export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
}
// Don't startOf(intervalUnit) here — dayjs uses Sunday-start weeks, which would
// drift Monday-aligned dates backward and bias every fractional index by 1/7.
- const firstDate = dayjsLocalToTimezone(dates[0], timezone)
+ const firstDate = parseDateInTimezone(dates[0], timezone)
const lastIndex = dates.length - 1
return Object.entries(groupedAnnotations)
.map(([dateKey, annotations]) => {
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/dates.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/dates.ts
index f443cad9fad0..1388f726fd22 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/dates.ts
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/dates.ts
@@ -1,4 +1,5 @@
-import { dayjs, Dayjs } from 'lib/dayjs'
+import { Dayjs } from 'lib/dayjs'
+import { parseDateInTimezone } from 'lib/utils/dateTimeUtils'
/** Bucket size for a date-based X axis. Mirrors `IntervalType` from product code without
* coupling hog-charts to it. */
@@ -53,25 +54,7 @@ export function createXAxisTickCallback({
}
}
-/** Parse a date string as a wall-clock time in the given timezone.
- *
- * All strings from ClickHouse — both datetime ("2026-03-08 14:00:00") and
- * date-only ("2026-03-08") — already have wall-clock digits in the project
- * timezone because ClickHouse applies toTimeZone before truncation. */
-export function parseDateForAxis(dateStr: string, timezone: string): Dayjs {
- const hasTime = dateStr.includes(' ') || dateStr.includes('T')
- try {
- // Parse as UTC so the result is browser-timezone-independent.
- // (dayjs.tz(string, tz) goes through new Date() which uses the
- // browser's local timezone and can shift dates during DST.)
- const utc = hasTime ? dayjs.utc(dateStr) : dayjs.utc(dateStr + ' 00:00:00')
- // keepLocalTime: true preserves the wall-clock digits while
- // attaching the project timezone — no conversion arithmetic.
- return utc.isValid() ? utc.tz(timezone, true) : dayjs(null)
- } catch {
- return dayjs(null)
- }
-}
+export const parseDateForAxis = parseDateInTimezone
function pickMode(interval: TimeInterval, parsedDates: Dayjs[], first: Dayjs, last: Dayjs): TickMode {
const spanMonths = (last.year() - first.year()) * 12 + last.month() - first.month()
diff --git a/frontend/src/lib/utils/dateTimeUtils.test.ts b/frontend/src/lib/utils/dateTimeUtils.test.ts
new file mode 100644
index 000000000000..984d00ec06df
--- /dev/null
+++ b/frontend/src/lib/utils/dateTimeUtils.test.ts
@@ -0,0 +1,47 @@
+import { dayjs } from 'lib/dayjs'
+
+import { parseDateInTimezone } from './dateTimeUtils'
+
+describe('parseDateInTimezone', () => {
+ describe('date-only strings', () => {
+ it.each([
+ ['UTC', '+00:00'],
+ ['America/Los_Angeles', '-07:00'],
+ ['Asia/Tokyo', '+09:00'],
+ ['Europe/Berlin', '+02:00'],
+ ])('treats "2026-05-05" as wall-clock midnight in project tz %s', (timezone, expectedOffset) => {
+ const out = parseDateInTimezone('2026-05-05', timezone)
+ expect(out.format('YYYY-MM-DD HH:mm Z')).toEqual(`2026-05-05 00:00 ${expectedOffset}`)
+ })
+
+ it('returns the same calendar day across browser timezones (no DST drift)', () => {
+ // The chart x-axis renders this with a 'D MMM' or 'MMM D' format.
+ // Across DST boundaries and across browser timezones, the calendar day
+ // for a date-only string must not shift by ±1 day.
+ const out = parseDateInTimezone('2026-03-08', 'America/Los_Angeles')
+ expect(out.format('D MMM YYYY')).toEqual('8 Mar 2026')
+ })
+ })
+
+ describe('strings with explicit timezone offset', () => {
+ it('treats Z-suffixed timestamps as real instants and converts to project tz', () => {
+ // 2024-04-28 23:30 UTC = 2024-04-29 08:30 in Tokyo.
+ const out = parseDateInTimezone('2024-04-28T23:30:00Z', 'Asia/Tokyo')
+ expect(out.format('YYYY-MM-DD HH:mm Z')).toEqual('2024-04-29 08:30 +09:00')
+ })
+
+ it('treats +HH:MM offsets as real instants', () => {
+ // 2024-04-28 00:00 -07:00 = 2024-04-28 07:00 UTC = 2024-04-28 16:00 Tokyo.
+ const out = parseDateInTimezone('2024-04-28T00:00:00-07:00', 'Asia/Tokyo')
+ expect(out.format('YYYY-MM-DD HH:mm Z')).toEqual('2024-04-28 16:00 +09:00')
+ })
+ })
+
+ describe('invalid inputs', () => {
+ it('returns an invalid Dayjs for unparseable strings instead of throwing', () => {
+ const out = parseDateInTimezone('not-a-date', 'UTC')
+ expect(dayjs.isDayjs(out)).toBe(true)
+ expect(out.isValid()).toBe(false)
+ })
+ })
+})
diff --git a/frontend/src/lib/utils/dateTimeUtils.ts b/frontend/src/lib/utils/dateTimeUtils.ts
index cc39ebda43d5..6874bc289224 100644
--- a/frontend/src/lib/utils/dateTimeUtils.ts
+++ b/frontend/src/lib/utils/dateTimeUtils.ts
@@ -114,3 +114,30 @@ export function formatLocalizedDate(): string {
return usDateLocales.some((usLocale) => localLang.startsWith(usLocale)) ? 'MMM DD' : 'DD MMM'
}
+
+/** Parse a date string into a Dayjs in the given timezone, browser-tz-independent.
+ *
+ * - Strings without explicit timezone info ("2026-03-08", "2026-03-08 14:00:00")
+ * are treated as wall-clock time in the given timezone. Strings from ClickHouse
+ * already have wall-clock digits in the project timezone because ClickHouse applies
+ * toTimeZone before truncation, and date-only buckets from the trends backend
+ * have no time component to convert.
+ * - Strings with explicit timezone info (trailing "Z" or "±HH:MM") are real instants;
+ * parse them as such and convert into the requested timezone.
+ *
+ * Don't use the `dayjs.utc(...).tz(timezone, true)` shape: keepLocalTime reads the
+ * **system** local representation of the underlying instant, not the UTC
+ * representation, so when the browser tz is east of UTC (e.g. Berlin, Tokyo) the
+ * calendar date shifts back by one day. */
+export function parseDateInTimezone(dateStr: string, timezone: string): dayjs.Dayjs {
+ const hasExplicitTz = /([Zz]|[+-]\d{2}:?\d{2})$/.test(dateStr)
+ try {
+ if (hasExplicitTz) {
+ const instant = dayjs(dateStr)
+ return instant.isValid() ? instant.tz(timezone) : dayjs(null)
+ }
+ return dayjs.tz(dateStr, timezone)
+ } catch {
+ return dayjs(null)
+ }
+}
diff --git a/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.test.ts b/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.test.ts
index 841530ac4359..6ee24c25a965 100644
--- a/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.test.ts
+++ b/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.test.ts
@@ -113,6 +113,24 @@ describe('getFormattedDate', () => {
expect(getFormattedDate(timestamp, { timezone: 'Asia/Tokyo' })).toEqual('29 Apr 2024')
})
+ // Regression: date-only strings from the trends backend (e.g. "2024-05-01") must
+ // format to the same day regardless of the project timezone. The previous
+ // implementation used dayjs.tz(string, tz) which goes through new Date() and could
+ // shift the date by a day, leaving the tooltip header out of sync with the x-axis.
+ it.each(['UTC', 'America/Los_Angeles', 'Asia/Tokyo'])(
+ 'preserves wall-clock date for date-only daily input in timezone %s',
+ (timezone) => {
+ expect(getFormattedDate('2024-05-01', { interval: 'day', timezone })).toEqual('1\u00A0May\u00A02024')
+ }
+ )
+
+ it('preserves wall-clock date across a US DST boundary', () => {
+ // Spring-forward day in the US — make sure date-only input still maps cleanly.
+ expect(getFormattedDate('2024-03-10', { interval: 'day', timezone: 'America/Los_Angeles' })).toEqual(
+ '10\u00A0Mar\u00A02024'
+ )
+ })
+
it('returns the correct week range with provided timezone', () => {
// Test that the week range is correct in a specific timezone
const timestamp = '2025-06-15T23:59:59-07:00' // PDT
@@ -130,8 +148,8 @@ describe('getFormattedDate', () => {
})
describe('with invalid inputs', () => {
- it('throws an error for invalid date string', () => {
- expect(() => getFormattedDate('invalid-date')).toThrow()
+ it('returns the raw input for an unparseable date string', () => {
+ expect(getFormattedDate('invalid-date')).toEqual('invalid-date')
})
it('expects undefined string if no inputs', () => {
diff --git a/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.tsx b/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.tsx
index 3693fcad6fbe..c6302834e18d 100644
--- a/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.tsx
+++ b/frontend/src/scenes/insights/InsightTooltip/insightTooltipUtils.tsx
@@ -3,7 +3,7 @@ import React from 'react'
import { parseAliasToReadable } from 'lib/components/PathCleanFilters/PathCleanFilterItem'
import { dayjs } from 'lib/dayjs'
import { capitalizeFirstLetter, midEllipsis, pluralize } from 'lib/utils'
-import { getConstrainedWeekRange } from 'lib/utils/dateTimeUtils'
+import { getConstrainedWeekRange, parseDateInTimezone } from 'lib/utils/dateTimeUtils'
import { cohortsModel } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
@@ -151,15 +151,22 @@ export function getFormattedDate(input?: string | number, options?: FormattedDat
return input
}
- const day = dayjs.tz(input, timezone)
+ const tz = timezone ?? 'UTC'
+ const day = typeof input === 'string' ? parseDateInTimezone(input, tz) : dayjs.tz(input, tz)
if (input === undefined || !day.isValid()) {
return String(input)
}
// Handle week interval separately
if (interval === 'week') {
- const dateFrom = dayjs.tz(dateRange?.date_from, timezone)
- const dateTo = dayjs.tz(dateRange?.date_to, timezone)
+ const dateFrom =
+ typeof dateRange?.date_from === 'string'
+ ? parseDateInTimezone(dateRange.date_from, tz)
+ : dayjs.tz(dateRange?.date_from, tz)
+ const dateTo =
+ typeof dateRange?.date_to === 'string'
+ ? parseDateInTimezone(dateRange.date_to, tz)
+ : dayjs.tz(dateRange?.date_to, tz)
const { start: weekStart, end: weekEnd } = getConstrainedWeekRange(
day,
{ start: dateFrom, end: dateTo },