Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

fix timezones (#785)

Bill Yang6dc29640de5b
diff --git a/client/src/app/[site]/errors/components/ErrorDetails.tsx b/client/src/app/[site]/errors/components/ErrorDetails.tsx
index 42e52e2c9..ed547acbc 100644
--- a/client/src/app/[site]/errors/components/ErrorDetails.tsx
+++ b/client/src/app/[site]/errors/components/ErrorDetails.tsx
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { userLocale } from "@/lib/dateTimeUtils";
+import { getTimezone } from "@/lib/store";
import { useGetRegionName } from "@/lib/geo";
import { getCountryName } from "@/lib/utils";
import { AlertTriangle, Code, Hash, Laptop, Loader2, Smartphone, TriangleAlert, User } from "lucide-react";
@@ -61,7 +62,7 @@ function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {
};
const formatTimestamp = (timestamp: string) => {
- return DateTime.fromSQL(timestamp, { zone: "utc" }).setLocale(userLocale).toRelative();
+ return DateTime.fromSQL(timestamp, { zone: getTimezone() }).setLocale(userLocale).toRelative();
};
return (
diff --git a/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx b/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx
index 7069ec131..cee110265 100644
--- a/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx
+++ b/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx
@@ -3,6 +3,7 @@
import { GetErrorBucketedResponse } from "@/api/analytics/endpoints";
import { hour12, userLocale } from "@/lib/dateTimeUtils";
import { useNivoTheme } from "@/lib/nivo";
+import { getTimezone } from "@/lib/store";
import { ResponsiveBar } from "@nivo/bar";
import { DateTime } from "luxon";
import { useMemo } from "react";
@@ -16,6 +17,7 @@ interface ErrorSparklineChartProps {
export function ErrorSparklineChart({ data, isHovering, errorMessage, isLoading }: ErrorSparklineChartProps) {
const nivoTheme = useNivoTheme();
+ const timezone = getTimezone();
const chartData = useMemo(() => {
if (!data || data.length === 0) {
@@ -25,13 +27,13 @@ export function ErrorSparklineChart({ data, isHovering, errorMessage, isLoading
return data
.filter(e => {
// Filter out dates from the future
- return DateTime.fromSQL(e.time).toUTC() <= DateTime.now();
+ return DateTime.fromSQL(e.time, { zone: timezone }).toUTC() <= DateTime.now();
})
.map(e => ({
- time: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
+ time: DateTime.fromSQL(e.time, { zone: timezone }).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
errors: e.error_count || 0,
}));
- }, [data]);
+ }, [data, timezone]);
if (isLoading) {
return (
@@ -76,7 +78,7 @@ export function ErrorSparklineChart({ data, isHovering, errorMessage, isLoading
value: number;
data: { time: string; errors: number };
}) => {
- const currentTime = DateTime.fromFormat(data.time, "yyyy-MM-dd HH:mm:ss", { zone: "utc" }).toLocal();
+ const currentTime = DateTime.fromFormat(data.time, "yyyy-MM-dd HH:mm:ss", { zone: "utc" }).setZone(getTimezone());
const currentY = Number(value);
return (
@@ -85,7 +87,7 @@ export function ErrorSparklineChart({ data, isHovering, errorMessage, isLoading
style={{ zIndex: 9999, position: "relative" }}
>
<div className="font-semibold mb-1 text-neutral-700 dark:text-neutral-200">
- {formatDateTime(currentTime)}
+ {formatDateTime(currentTime, timezone)}
</div>
<div className="flex justify-between items-center">
<span className="font-medium text-red-400">
@@ -102,13 +104,14 @@ export function ErrorSparklineChart({ data, isHovering, errorMessage, isLoading
);
}
-const formatDateTime = (dt: DateTime) => {
+const formatDateTime = (dt: DateTime, tz: string) => {
const options: Intl.DateTimeFormatOptions = {
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
hour12: hour12,
+ timeZone: tz,
};
return new Intl.DateTimeFormat(userLocale, options).format(dt.toJSDate());
diff --git a/client/src/app/[site]/events/components/EventLogItem.tsx b/client/src/app/[site]/events/components/EventLogItem.tsx
index 8d0878adb..c21d8959b 100644
--- a/client/src/app/[site]/events/components/EventLogItem.tsx
+++ b/client/src/app/[site]/events/components/EventLogItem.tsx
@@ -2,6 +2,7 @@
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { getTimezone } from "@/lib/store";
import { ExternalLink, Eye, Laptop, MousePointerClick, Smartphone } from "lucide-react";
import { DateTime } from "luxon";
import Link from "next/link";
@@ -44,7 +45,7 @@ export function EventLogItem({ event }: EventLogItemProps) {
// Parse event timestamp
const eventTime = DateTime.fromSQL(event.timestamp, {
zone: "utc",
- }).toLocal();
+ }).setZone(getTimezone());
// Determine event type
const isPageview = event.type === "pageview";
diff --git a/client/src/app/[site]/events/components/OutboundLinksList.tsx b/client/src/app/[site]/events/components/OutboundLinksList.tsx
index 80e10d5be..8b3c3bd89 100644
--- a/client/src/app/[site]/events/components/OutboundLinksList.tsx
+++ b/client/src/app/[site]/events/components/OutboundLinksList.tsx
@@ -1,5 +1,6 @@
"use client";
+import { getTimezone } from "@/lib/store";
import NumberFlow from "@number-flow/react";
import { Info } from "lucide-react";
import { DateTime } from "luxon";
@@ -122,7 +123,7 @@ export function OutboundLinksList({ outboundLinks, isLoading, size = "small" }:
const percentage = (link.count / totalCount) * 100;
const lastClicked = DateTime.fromSQL(link.lastClicked, {
zone: "utc",
- }).toLocal();
+ }).setZone(getTimezone());
return (
<div
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
index 54774e2d3..02da2d63f 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
@@ -12,14 +12,16 @@ import { calculateWindowSize } from "../../../timelineUtils";
import { MAX_PAGES, PAGE_SIZE } from "./timelineLayerConstants";
export function useTimelineSessions() {
- const { time, site } = useStore();
+ const { time, site, timezone: storeTimezone } = useStore();
const { manualWindowSize, setTimeRange, setWindowSize, setAllSessions, setLoading, setError } = useTimelineStore();
+ // Resolve "system" to actual timezone, but keep reactivity from useStore
+ const timezone = storeTimezone === "system" ? Intl.DateTimeFormat().resolvedOptions().timeZone : storeTimezone;
const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
// Fetch all sessions with pagination (up to 5 pages, 50k sessions total)
const { data, isLoading, isError } = useQuery<APIResponse<GetSessionsResponse> & { hasMoreData?: boolean }>({
- queryKey: ["timeline-sessions", time, site, filteredFilters],
+ queryKey: ["timeline-sessions", time, site, filteredFilters, timezone],
queryFn: async () => {
const allSessions = [];
let reachedMaxPages = false;
@@ -89,8 +91,8 @@ export function useTimelineSessions() {
let latest: DateTime | null = null;
allSessions.forEach(session => {
- const start = DateTime.fromSQL(session.session_start, { zone: "utc" }).toLocal();
- const end = DateTime.fromSQL(session.session_end, { zone: "utc" }).toLocal();
+ const start = DateTime.fromSQL(session.session_start, { zone: "utc" }).setZone(timezone);
+ const end = DateTime.fromSQL(session.session_end, { zone: "utc" }).setZone(timezone);
if (!earliest || start < earliest) {
earliest = start;
@@ -108,5 +110,5 @@ export function useTimelineSessions() {
}
setTimeRange(earliest, latest);
}
- }, [allSessions, setTimeRange, setWindowSize, manualWindowSize, time]);
+ }, [allSessions, setTimeRange, setWindowSize, manualWindowSize, time, timezone]);
}
diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsx
index eadd0e4fe..1f2a1f3c2 100644
--- a/client/src/app/[site]/globe/components/GlobeSessions.tsx
+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx
@@ -1,3 +1,4 @@
+import { getTimezone } from "@/lib/store";
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
import { ArrowRight, ChevronDown, ChevronUp } from "lucide-react";
import { DateTime } from "luxon";
@@ -65,8 +66,8 @@ function SessionCardSkeleton() {
function SessionCard({ session, onClick }: { session: GetSessionsResponse[number]; onClick?: () => void }) {
// Calculate session duration in minutes
- const start = DateTime.fromSQL(session.session_start);
- const end = DateTime.fromSQL(session.session_end);
+ const start = DateTime.fromSQL(session.session_start, { zone: "utc" });
+ const end = DateTime.fromSQL(session.session_end, { zone: "utc" });
const totalSeconds = Math.floor(end.diff(start).milliseconds / 1000);
const duration = formatShortDuration(totalSeconds);
const siteId = useCurrentSite();
@@ -90,7 +91,7 @@ function SessionCard({ session, onClick }: { session: GetSessionsResponse[number
zone: "utc",
})
.setLocale(userLocale)
- .toLocal()
+ .setZone(getTimezone())
.toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm")}
</span>
<span className="text-neutral-400">•</span>
diff --git a/client/src/app/[site]/globe/components/TimelineScrubber.tsx b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
index 8fa9ac20f..695d272ce 100644
--- a/client/src/app/[site]/globe/components/TimelineScrubber.tsx
+++ b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
@@ -3,6 +3,7 @@ import { AlertTriangle, Pause, Play } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { TimelineSlider } from "../../../../components/ui/timeline-slider";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "../../../../components/ui/tooltip";
+import { useStore } from "../../../../lib/store";
import { useTimelineStore, useActiveSessions } from "../timelineStore";
import { formatTimelineTime, generateTimeWindows, getSessionCountsPerWindow } from "../timelineUtils";
import { MAX_PAGES, PAGE_SIZE } from "../3d/hooks/timelineLayer/timelineLayerConstants";
@@ -11,6 +12,9 @@ export function TimelineScrubber() {
const { currentTime, timeRange, windowSize, setCurrentTime, allSessions, isLoading, hasMoreData } =
useTimelineStore();
const activeSessions = useActiveSessions();
+ // Use reactive timezone from useStore
+ const storeTimezone = useStore(state => state.timezone);
+ const timezone = storeTimezone === "system" ? Intl.DateTimeFormat().resolvedOptions().timeZone : storeTimezone;
const [isPlaying, setIsPlaying] = useState(false);
const [localSliderIndex, setLocalSliderIndex] = useState(0);
const [displayedCounts, setDisplayedCounts] = useState<number[]>([]);
@@ -92,13 +96,13 @@ export function TimelineScrubber() {
// Debounced function to calculate session counts
const debouncedCalculateCounts = useRef(
- debounce((windows: ReturnType<typeof generateTimeWindows>, sessions: typeof allSessions, size: number) => {
+ debounce((windows: ReturnType<typeof generateTimeWindows>, sessions: typeof allSessions, size: number, tz: string) => {
if (windows.length === 0 || sessions.length === 0) {
setDisplayedCounts([]);
setIsCalculating(false);
return;
}
- const counts = getSessionCountsPerWindow(sessions, windows, size);
+ const counts = getSessionCountsPerWindow(sessions, windows, size, tz);
setDisplayedCounts(counts);
setIsCalculating(false);
}, 200)
@@ -125,12 +129,12 @@ export function TimelineScrubber() {
useEffect(() => {
if (timeWindows.length > 0 && allSessions.length > 0) {
setIsCalculating(true);
- debouncedCalculateCounts(timeWindows, allSessions, windowSize);
+ debouncedCalculateCounts(timeWindows, allSessions, windowSize, timezone);
} else {
setDisplayedCounts([]);
setIsCalculating(false);
}
- }, [timeWindows, allSessions, windowSize, debouncedCalculateCounts]);
+ }, [timeWindows, allSessions, windowSize, timezone, debouncedCalculateCounts]);
// Get max count for scaling the histogram
const maxCount = useMemo(() => {
diff --git a/client/src/app/[site]/globe/timelineStore.ts b/client/src/app/[site]/globe/timelineStore.ts
index d89f0182b..26eca5dff 100644
--- a/client/src/app/[site]/globe/timelineStore.ts
+++ b/client/src/app/[site]/globe/timelineStore.ts
@@ -2,6 +2,7 @@ import { DateTime } from "luxon";
import { create } from "zustand";
import { useMemo } from "react";
import type { GetSessionsResponse } from "../../../api/analytics/endpoints";
+import { useStore } from "../../../lib/store";
import { getActiveSessions } from "./timelineUtils";
interface TimelineStore {
@@ -58,10 +59,13 @@ export function useActiveSessions(): GetSessionsResponse {
const currentTime = useTimelineStore(state => state.currentTime);
const windowSize = useTimelineStore(state => state.windowSize);
const allSessions = useTimelineStore(state => state.allSessions);
+ // Use reactive timezone from useStore
+ const storeTimezone = useStore(state => state.timezone);
+ const timezone = storeTimezone === "system" ? Intl.DateTimeFormat().resolvedOptions().timeZone : storeTimezone;
return useMemo(() => {
if (!currentTime || allSessions.length === 0) return [];
- const activeSessions = getActiveSessions(allSessions, currentTime, windowSize);
+ const activeSessions = getActiveSessions(allSessions, currentTime, windowSize, timezone);
return activeSessions;
- }, [currentTime, windowSize, allSessions]);
+ }, [currentTime, windowSize, allSessions, timezone]);
}
diff --git a/client/src/app/[site]/globe/timelineUtils.ts b/client/src/app/[site]/globe/timelineUtils.ts
index a792ccd22..7b4c32328 100644
--- a/client/src/app/[site]/globe/timelineUtils.ts
+++ b/client/src/app/[site]/globe/timelineUtils.ts
@@ -1,4 +1,5 @@
import { DateTime } from "luxon";
+import { getTimezone } from "../../../lib/store";
import { GetSessionsResponse } from "../../../api/analytics/endpoints";
/**
@@ -59,10 +60,12 @@ export function generateTimeWindows(startTime: DateTime, endTime: DateTime, wind
export function sessionOverlapsWindow(
session: GetSessionsResponse[number],
windowStart: DateTime,
- windowEnd: DateTime
+ windowEnd: DateTime,
+ timezone?: string
): boolean {
- const sessionStart = DateTime.fromSQL(session.session_start, { zone: "utc" }).toLocal();
- const sessionEnd = DateTime.fromSQL(session.session_end, { zone: "utc" }).toLocal();
+ const tz = timezone ?? getTimezone();
+ const sessionStart = DateTime.fromSQL(session.session_start, { zone: "utc" }).setZone(tz);
+ const sessionEnd = DateTime.fromSQL(session.session_end, { zone: "utc" }).setZone(tz);
// Session overlaps if:
// - It starts before the window ends AND
@@ -76,11 +79,12 @@ export function sessionOverlapsWindow(
export function getActiveSessions(
sessions: GetSessionsResponse,
windowStart: DateTime,
- windowSize: number
+ windowSize: number,
+ timezone?: string
): GetSessionsResponse {
const windowEnd = windowStart.plus({ minutes: windowSize });
- return sessions.filter(session => sessionOverlapsWindow(session, windowStart, windowEnd));
+ return sessions.filter(session => sessionOverlapsWindow(session, windowStart, windowEnd, timezone));
}
/**
@@ -90,15 +94,17 @@ export function getActiveSessions(
export function getSessionCountsPerWindow(
sessions: GetSessionsResponse,
timeWindows: DateTime[],
- windowSize: number
+ windowSize: number,
+ timezone?: string
): number[] {
+ const tz = timezone ?? getTimezone();
// Parse all session times once upfront and convert to epoch ms
const startTimes: number[] = [];
const endTimes: number[] = [];
for (const session of sessions) {
- const start = DateTime.fromSQL(session.session_start, { zone: "utc" }).toLocal();
- const end = DateTime.fromSQL(session.session_end, { zone: "utc" }).toLocal();
+ const start = DateTime.fromSQL(session.session_start, { zone: "utc" }).setZone(tz);
+ const end = DateTime.fromSQL(session.session_end, { zone: "utc" }).setZone(tz);
startTimes.push(start.toMillis());
endTimes.push(end.toMillis());
}
diff --git a/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts b/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts
index ba543e4f4..74f8ec4b5 100644
--- a/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts
+++ b/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts
@@ -1,5 +1,6 @@
import { DateTime } from "luxon";
import { createElement } from "react";
+import { getTimezone } from "../../../../lib/store";
// @ts-ignore - React 19 has built-in types
import { renderToStaticMarkup } from "react-dom/server";
import { Eye, MousePointerClick } from "lucide-react";
@@ -33,7 +34,7 @@ export function buildTooltipHTML(session: GetSessionsResponse[number], lng: numb
// Start time formatting
const startTime = DateTime.fromSQL(session.session_start, { zone: "utc" })
.setLocale(userLocale)
- .toLocal()
+ .setZone(getTimezone())
.toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm");
// Pageview and event icons
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 2b7b86d36..358d6003e 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -10,17 +10,17 @@ import { APIResponse } from "../../../../../api/types";
import { Time } from "../../../../../components/DateSelector/types";
import { formatSecondsAsMinutesAndSeconds, formatter } from "../../../../../lib/utils";
import { userLocale, hour12, formatChartDateTime } from "../../../../../lib/dateTimeUtils";
+import { getTimezone } from "../../../../../lib/store";
import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
-const getMax = (time: Time, bucket: TimeBucket) => {
- const now = DateTime.now();
+const getMax = (time: Time, bucket: TimeBucket, timezone: string) => {
if (time.mode === "past-minutes") {
if (bucket === "hour") {
- return DateTime.now().setZone("UTC").startOf("hour").toJSDate();
+ return DateTime.now().setZone(timezone).startOf("hour").toJSDate();
}
return undefined;
} else if (time.mode === "day") {
- const dayDate = DateTime.fromISO(time.day)
+ const dayDate = DateTime.fromISO(time.day, { zone: timezone })
.endOf("day")
.minus({
minutes:
@@ -34,12 +34,12 @@ const getMax = (time: Time, bucket: TimeBucket) => {
? 4
: 0,
});
- return now < dayDate ? dayDate.toJSDate() : undefined;
+ return dayDate.toJSDate();
} else if (time.mode === "range") {
if (bucket === "day" || bucket === "week" || bucket === "month" || bucket === "year") {
return undefined;
}
- const rangeDate = DateTime.fromISO(time.endDate)
+ const rangeDate = DateTime.fromISO(time.endDate, { zone: timezone })
.endOf("day")
.minus({
minutes:
@@ -53,54 +53,55 @@ const getMax = (time: Time, bucket: TimeBucket) => {
? 4
: 0,
});
- return now < rangeDate ? rangeDate.toJSDate() : undefined;
+ return rangeDate.toJSDate();
} else if (time.mode === "week") {
if (bucket === "hour") {
- const endDate = DateTime.fromISO(time.week).endOf("week").minus({
+ const endDate = DateTime.fromISO(time.week, { zone: timezone }).endOf("week").minus({
minutes: 59,
});
- return now < endDate ? endDate.toJSDate() : undefined;
+ return endDate.toJSDate();
}
if (bucket === "fifteen_minutes") {
- const endDate = DateTime.fromISO(time.week).endOf("week").minus({
+ const endDate = DateTime.fromISO(time.week, { zone: timezone }).endOf("week").minus({
minutes: 14,
});
- return now < endDate ? endDate.toJSDate() : undefined;
+ return endDate.toJSDate();
}
return undefined;
} else if (time.mode === "month") {
if (bucket === "hour") {
- const endDate = DateTime.fromISO(time.month).endOf("month").minus({
+ const endDate = DateTime.fromISO(time.month, { zone: timezone }).endOf("month").minus({
minutes: 59,
});
- return now < endDate ? endDate.toJSDate() : undefined;
+ return endDate.toJSDate();
}
- const monthDate = DateTime.fromISO(time.month).endOf("month");
- return now < monthDate ? monthDate.toJSDate() : undefined;
+ const monthDate = DateTime.fromISO(time.month, { zone: timezone }).endOf("month");
+ return monthDate.toJSDate();
} else if (time.mode === "year") {
- const yearDate = DateTime.fromISO(time.year).endOf("year");
- return now < yearDate ? yearDate.toJSDate() : undefined;
+ const yearDate = DateTime.fromISO(time.year, { zone: timezone }).endOf("year");
+ return yearDate.toJSDate();
}
return undefined;
};
-const getMin = (time: Time, bucket: TimeBucket) => {
+const getMin = (time: Time, bucket: TimeBucket, timezone: string) => {
if (time.mode === "past-minutes") {
return DateTime.now()
+ .setZone(timezone)
.minus({ minutes: time.pastMinutesStart })
.startOf(time.pastMinutesStart < 360 ? "minute" : "hour")
.toJSDate();
} else if (time.mode === "day") {
- const dayDate = DateTime.fromISO(time.day).startOf("day");
+ const dayDate = DateTime.fromISO(time.day, { zone: timezone }).startOf("day");
return dayDate.toJSDate();
} else if (time.mode === "week") {
- const weekDate = DateTime.fromISO(time.week).startOf("week");
+ const weekDate = DateTime.fromISO(time.week, { zone: timezone }).startOf("week");
return weekDate.toJSDate();
} else if (time.mode === "month") {
- const monthDate = DateTime.fromISO(time.month).startOf("month");
+ const monthDate = DateTime.fromISO(time.month, { zone: timezone }).startOf("month");
return monthDate.toJSDate();
} else if (time.mode === "year") {
- const yearDate = DateTime.fromISO(time.year).startOf("year");
+ const yearDate = DateTime.fromISO(time.year, { zone: timezone }).startOf("year");
return yearDate.toJSDate();
}
return undefined;
@@ -130,6 +131,10 @@ export function Chart({
const { time, bucket, selectedStat } = useStore();
const { width } = useWindowSize();
const nivoTheme = useNivoTheme();
+ const timezone = getTimezone();
+
+ const chartMin = getMin(time, bucket, timezone);
+ const chartMax = getMax(time, bucket, timezone);
const maxTicks = Math.round((width ?? Infinity) / 75);
@@ -140,8 +145,8 @@ export function Chart({
const formattedData =
data?.data
?.map((e, i) => {
- // Parse timestamp properly
- const timestamp = DateTime.fromSQL(e.time).toUTC();
+ // Parse timestamp in the selected timezone, then convert to UTC for chart
+ const timestamp = DateTime.fromSQL(e.time, { zone: timezone }).toUTC();
// filter out dates from the future
if (timestamp > DateTime.now()) {
@@ -154,7 +159,7 @@ export function Chart({
previousY: i >= lengthDiff && previousData?.data?.[i - lengthDiff][selectedStat],
currentTime: timestamp,
previousTime:
- i >= lengthDiff ? DateTime.fromSQL(previousData?.data?.[i - lengthDiff]?.time ?? "").toUTC() : undefined,
+ i >= lengthDiff ? DateTime.fromSQL(previousData?.data?.[i - lengthDiff]?.time ?? "", { zone: timezone }).toUTC() : undefined,
};
})
.filter(e => e !== null) || [];
@@ -253,8 +258,8 @@ export function Chart({
format: "%Y-%m-%d %H:%M:%S",
precision: "second",
useUTC: true,
- max: getMax(time, bucket),
- min: getMin(time, bucket),
+ max: chartMax,
+ min: chartMin,
}}
yScale={{
type: "linear",
@@ -281,7 +286,7 @@ export function Chart({
: Math.min(12, data?.data?.length ?? 0)
),
format: value => {
- const dt = DateTime.fromJSDate(value).setLocale(userLocale);
+ const dt = DateTime.fromJSDate(value, { zone: "utc" }).setZone(getTimezone()).setLocale(userLocale);
if (time.mode === "past-minutes") {
if (time.pastMinutesStart < 1440) {
return dt.toFormat(hour12 ? "h:mm" : "HH:mm");
diff --git a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
index 93e45df1a..d1668fb56 100644
--- a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
@@ -1,6 +1,6 @@
"use client";
import { useNivoTheme } from "@/lib/nivo";
-import { useStore } from "@/lib/store";
+import { getTimezone, useStore } from "@/lib/store";
import { useTheme } from "next-themes";
import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
@@ -9,18 +9,18 @@ import { APIResponse } from "../../../../../api/types";
import { Time } from "../../../../../components/DateSelector/types";
import { TimeBucket } from "@rybbit/shared";
-const getMin = (time: Time, bucket: TimeBucket) => {
+const getMin = (time: Time, bucket: TimeBucket, timezone: string) => {
if (time.mode === "day") {
- const dayDate = DateTime.fromISO(time.day).startOf("day");
+ const dayDate = DateTime.fromISO(time.day, { zone: timezone }).startOf("day");
return dayDate.toJSDate();
} else if (time.mode === "week") {
- const weekDate = DateTime.fromISO(time.week).startOf("week");
+ const weekDate = DateTime.fromISO(time.week, { zone: timezone }).startOf("week");
return weekDate.toJSDate();
} else if (time.mode === "month") {
- const monthDate = DateTime.fromISO(time.month).startOf("month");
+ const monthDate = DateTime.fromISO(time.month, { zone: timezone }).startOf("month");
return monthDate.toJSDate();
} else if (time.mode === "year") {
- const yearDate = DateTime.fromISO(time.year).startOf("year");
+ const yearDate = DateTime.fromISO(time.year, { zone: timezone }).startOf("year");
return yearDate.toJSDate();
}
// else if (time.mode === "past-minutes") {
@@ -47,10 +47,12 @@ export function PreviousChart({
const { resolvedTheme } = useTheme();
const nivoTheme = useNivoTheme();
+ const timezone = getTimezone();
const size = (data?.data.length ?? 0 / 2) + 1;
const formattedData = data?.data
?.map(e => {
- const timestamp = DateTime.fromSQL(e.time).toUTC();
+ // Parse timestamp in the selected timezone, then convert to UTC for chart
+ const timestamp = DateTime.fromSQL(e.time, { zone: timezone }).toUTC();
return {
x: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
y: e[selectedStat],
@@ -58,7 +60,7 @@ export function PreviousChart({
})
.slice(0, size);
- const min = getMin(time, bucket);
+ const min = getMin(time, bucket, timezone);
const maxPastMinutes =
time.mode === "past-minutes" && bucket === "hour"
? DateTime.now().setZone("UTC").minus({ minutes: time.pastMinutesStart }).startOf("hour").toJSDate()
@@ -101,7 +103,7 @@ export function PreviousChart({
truncateTickAt: 0,
tickValues: 0,
format: value => {
- const localTime = DateTime.fromJSDate(value).toLocal();
+ const localTime = DateTime.fromJSDate(value, { zone: "utc" }).setZone(getTimezone());
if ((time.mode === "past-minutes" && time.pastMinutesStart >= 1440) || time.mode === "day") {
return localTime.toFormat("ha");
diff --git a/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx b/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
index d8675c80c..2d9c52a55 100644
--- a/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
+++ b/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
@@ -2,6 +2,7 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
+import { getTimezone } from "@/lib/store";
import { useDebounce, useIntersectionObserver } from "@uidotdev/usehooks";
import { DateTime } from "luxon";
import { ChevronDown, ChevronUp, Loader2, Search, SquareArrowOutUpRight } from "lucide-react";
@@ -180,7 +181,7 @@ export function OutboundLinksDialog({ outboundLinks, expanded, close }: Outbound
<td className="px-2 py-2 text-right text-neutral-600 dark:text-neutral-300">
{(() => {
try {
- const dt = DateTime.fromSQL(row.lastClicked, { zone: "utc" }).toLocal();
+ const dt = DateTime.fromSQL(row.lastClicked, { zone: "utc" }).setZone(getTimezone());
return dt.toRelative();
} catch {
return "-";
diff --git a/client/src/app/[site]/main/components/sections/Weekdays.tsx b/client/src/app/[site]/main/components/sections/Weekdays.tsx
index fdb7198db..d66b45100 100644
--- a/client/src/app/[site]/main/components/sections/Weekdays.tsx
+++ b/client/src/app/[site]/main/components/sections/Weekdays.tsx
@@ -6,7 +6,7 @@ import { Tabs, TabsList, TabsTrigger } from "../../../../../components/ui/basic-
import { Card, CardContent, CardLoader } from "../../../../../components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../../../components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
-import { StatType, useStore } from "../../../../../lib/store";
+import { getTimezone, StatType, useStore } from "../../../../../lib/store";
import { cn } from "../../../../../lib/utils";
import { formatLocalTime, hourLabels, longDayNames, shortDayNames } from "../../../../../lib/dateTimeUtils";
@@ -14,6 +14,7 @@ import { formatLocalTime, hourLabels, longDayNames, shortDayNames } from "../../
export function Weekdays() {
const { site, time } = useStore();
const [metric, setMetric] = useState<StatType>("users");
+ const timezone = getTimezone();
const { data, isFetching, error } = useGetOverviewBucketed({
site,
@@ -38,8 +39,8 @@ export function Weekdays() {
data.data.forEach(item => {
if (!item || !item.time) return;
- // Parse the timestamp
- const date = DateTime.fromSQL(item.time);
+ // Parse the timestamp in the selected timezone
+ const date = DateTime.fromSQL(item.time, { zone: timezone });
if (!date.isValid) return;
const dayOfWeek = (date.weekday - 1) % 7; // Luxon uses 1 for Monday, 7 for Sunday
@@ -63,7 +64,7 @@ export function Weekdays() {
}
return aggregated;
- }, [data, metric]);
+ }, [data, metric, timezone]);
// Find max value for color intensity scaling
const maxValue = useMemo(() => {
diff --git a/client/src/app/[site]/pages/components/PageSparklineChart.tsx b/client/src/app/[site]/pages/components/PageSparklineChart.tsx
index 8d17b3cc9..37d04e938 100644
--- a/client/src/app/[site]/pages/components/PageSparklineChart.tsx
+++ b/client/src/app/[site]/pages/components/PageSparklineChart.tsx
@@ -5,6 +5,7 @@ import { APIResponse } from "@/api/types";
import { ChartTooltip } from "@/components/charts/ChartTooltip";
import { hour12, userLocale } from "@/lib/dateTimeUtils";
import { useNivoTheme } from "@/lib/nivo";
+import { getTimezone } from "@/lib/store";
import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
@@ -17,6 +18,8 @@ interface PageSparklineChartProps {
export function PageSparklineChart({ data, isHovering, pageTitle, isLoading }: PageSparklineChartProps) {
const nivoTheme = useNivoTheme();
+ const timezone = getTimezone();
+
if (isLoading) {
return (
<div className="h-full w-full flex items-center justify-center animate-pulse">
@@ -29,12 +32,12 @@ export function PageSparklineChart({ data, isHovering, pageTitle, isLoading }: P
const sparklineData = data?.data
?.filter(e => {
// Filter out dates from the future
- return DateTime.fromSQL(e.time).toUTC() <= DateTime.now();
+ return DateTime.fromSQL(e.time, { zone: timezone }).toUTC() <= DateTime.now();
})
.map(e => ({
- x: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
+ x: DateTime.fromSQL(e.time, { zone: timezone }).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
y: e.sessions || 0,
- time: DateTime.fromSQL(e.time).toUTC(),
+ time: DateTime.fromSQL(e.time, { zone: timezone }).toUTC(),
}));
if (!sparklineData || sparklineData.length === 0) {
@@ -102,7 +105,7 @@ export function PageSparklineChart({ data, isHovering, pageTitle, isLoading }: P
<ChartTooltip>
<div className="p-2">
<div className="flex items-center justify-between gap-3">
- <div>{formatDateTime(timestamp)}</div>
+ <div>{formatDateTime(timestamp, timezone)}</div>
<div className="font-medium">{value.toLocaleString()}</div>
</div>
</div>
@@ -113,13 +116,14 @@ export function PageSparklineChart({ data, isHovering, pageTitle, isLoading }: P
);
}
-const formatDateTime = (dt: DateTime) => {
+const formatDateTime = (dt: DateTime, tz: string) => {
const options: Intl.DateTimeFormatOptions = {
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
hour12: hour12,
+ timeZone: tz,
};
return new Intl.DateTimeFormat(userLocale, options).format(dt.toJSDate());
diff --git a/client/src/app/[site]/performance/components/PerformanceChart.tsx b/client/src/app/[site]/performance/components/PerformanceChart.tsx
index cbc6bc0f5..e86657cba 100644
--- a/client/src/app/[site]/performance/components/PerformanceChart.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceChart.tsx
@@ -13,7 +13,7 @@ import { BucketSelection } from "../../../../components/BucketSelection";
import { RybbitLogo } from "../../../../components/RybbitLogo";
import { authClient } from "../../../../lib/auth";
import { formatChartDateTime, hour12, userLocale } from "../../../../lib/dateTimeUtils";
-import { useStore } from "../../../../lib/store";
+import { getTimezone, useStore } from "../../../../lib/store";
import { cn } from "../../../../lib/utils";
import { usePerformanceStore } from "../performanceStore";
import { formatMetricValue, getMetricUnit, getPerformanceThresholds, METRIC_LABELS } from "../utils/performanceUtils";
@@ -31,6 +31,7 @@ export function PerformanceChart() {
const { selectedPerformanceMetric, selectedPercentile } = usePerformanceStore();
const nivoTheme = useNivoTheme();
const { isWhiteLabel } = useWhiteLabel();
+ const timezone = getTimezone();
// State for toggling percentile visibility
const [visiblePercentiles, setVisiblePercentiles] = useState<Set<string>>(new Set(["P50", "P75", "P90", "P99"]));
@@ -59,8 +60,8 @@ export function PerformanceChart() {
const processedData =
timeSeriesData?.data
?.map((item: any) => {
- // Parse timestamp properly using luxon (same as Chart.tsx)
- const timestamp = DateTime.fromSQL(item.time).toUTC();
+ // Parse timestamp in the selected timezone, then convert to UTC for chart
+ const timestamp = DateTime.fromSQL(item.time, { zone: timezone }).toUTC();
// Filter out dates from the future
if (timestamp > DateTime.now()) {
@@ -129,7 +130,7 @@ export function PerformanceChart() {
].filter(series => series.data.length > 0 && visiblePercentiles.has(series.id));
const formatXAxisValue = (value: any) => {
- const dt = DateTime.fromJSDate(value).setLocale(userLocale);
+ const dt = DateTime.fromJSDate(value, { zone: "utc" }).setZone(timezone).setLocale(userLocale);
if (
bucket === "hour" ||
bucket === "minute" ||
@@ -299,7 +300,7 @@ export function PerformanceChart() {
markers={markers}
lineWidth={1}
sliceTooltip={({ slice }: any) => {
- const currentTime = DateTime.fromJSDate(new Date(slice.points[0].data.x));
+ const currentTime = DateTime.fromJSDate(new Date(slice.points[0].data.x), { zone: "utc" }).setZone(timezone);
return (
<ChartTooltip>
diff --git a/client/src/app/[site]/replay/components/ReplayCard.tsx b/client/src/app/[site]/replay/components/ReplayCard.tsx
index aa71623fb..cc8e19d41 100644
--- a/client/src/app/[site]/replay/components/ReplayCard.tsx
+++ b/client/src/app/[site]/replay/components/ReplayCard.tsx
@@ -1,3 +1,4 @@
+import { getTimezone } from "@/lib/store";
import { Clock, MousePointerClick, Trash2 } from "lucide-react";
import { DateTime } from "luxon";
import { useState } from "react";
@@ -55,7 +56,7 @@ export function ReplayCard({ replay }: { replay: SessionReplayListItem }) {
const deleteSessionReplay = useDeleteSessionReplay();
const startTime = DateTime.fromSQL(replay.start_time, {
zone: "utc",
- }).toLocal();
+ }).setZone(getTimezone());
const duration = replay.duration_ms ? Math.ceil(replay.duration_ms / 1000) : null;
const formatDuration = (seconds: number) => {
diff --git a/client/src/app/[site]/user/[userId]/components/Calendar.tsx b/client/src/app/[site]/user/[userId]/components/Calendar.tsx
index 5b19c553b..5447bcd38 100644
--- a/client/src/app/[site]/user/[userId]/components/Calendar.tsx
+++ b/client/src/app/[site]/user/[userId]/components/Calendar.tsx
@@ -1,3 +1,4 @@
+import { getTimezone } from "@/lib/store";
import { ResponsiveTimeRange } from "@nivo/calendar";
import _ from "lodash";
import { DateTime } from "luxon";
@@ -13,7 +14,7 @@ export const VisitCalendar = ({ sessionCount }: { sessionCount: UserSessionCount
.map(e => ({
value: e.sessions,
day: DateTime.fromSQL(e.date ?? 0, { zone: "utc" })
- .toLocal()
+ .setZone(getTimezone())
.toFormat("y-LL-dd"),
}))
.reverse();
diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
index 8d545e0a8..f4f5643aa 100644
--- a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
@@ -1,5 +1,6 @@
"use client";
+import { getTimezone } from "@/lib/store";
import { Calendar, CalendarCheck, Clock, Files, Globe, Laptop, Monitor, Smartphone, Tablet } from "lucide-react";
import { DateTime } from "luxon";
import { Avatar, generateName } from "../../../../../components/Avatar";
@@ -122,7 +123,7 @@ export function UserSidebar({ data, isLoading, sessionCount, getRegionName }: Us
label="First Seen"
value={
data?.first_seen
- ? DateTime.fromSQL(data.first_seen, { zone: "utc" }).toLocal().toLocaleString(DateTime.DATE_MED)
+ ? DateTime.fromSQL(data.first_seen, { zone: "utc" }).setZone(getTimezone()).toLocaleString(DateTime.DATE_MED)
: "—"
}
isLoading={isLoading}
@@ -132,7 +133,7 @@ export function UserSidebar({ data, isLoading, sessionCount, getRegionName }: Us
label="Last Seen"
value={
data?.last_seen
- ? DateTime.fromSQL(data.last_seen, { zone: "utc" }).toLocal().toLocaleString(DateTime.DATE_MED)
+ ? DateTime.fromSQL(data.last_seen, { zone: "utc" }).setZone(getTimezone()).toLocaleString(DateTime.DATE_MED)
: "—"
}
isLoading={isLoading}
diff --git a/client/src/app/[site]/users/page.tsx b/client/src/app/[site]/users/page.tsx
index ddb8ad662..09084b4ec 100644
--- a/client/src/app/[site]/users/page.tsx
+++ b/client/src/app/[site]/users/page.tsx
@@ -9,6 +9,7 @@ import {
SortingState,
useReactTable,
} from "@tanstack/react-table";
+import { getTimezone } from "@/lib/store";
import { ArrowDown, ArrowUp, ArrowUpDown, Monitor, Smartphone, Tablet } from "lucide-react";
import { DateTime } from "luxon";
import Link from "next/link";
@@ -93,7 +94,7 @@ export default function UsersPage() {
// Format relative time with special handling for times less than 1 minute
const formatRelativeTime = (dateStr: string) => {
- const date = DateTime.fromSQL(dateStr, { zone: "utc" }).toLocal();
+ const date = DateTime.fromSQL(dateStr, { zone: "utc" }).setZone(getTimezone());
const diff = Math.abs(date.diffNow(["minutes"]).minutes);
if (diff < 1) {
@@ -219,7 +220,7 @@ export default function UsersPage() {
cell: info => {
const date = DateTime.fromSQL(info.getValue(), {
zone: "utc",
- }).toLocal();
+ }).setZone(getTimezone());
const formattedDate = date.toLocaleString(DateTime.DATETIME_SHORT);
const relativeTime = formatRelativeTime(info.getValue());
@@ -242,7 +243,7 @@ export default function UsersPage() {
cell: info => {
const date = DateTime.fromSQL(info.getValue(), {
zone: "utc",
- }).toLocal();
+ }).setZone(getTimezone());
const formattedDate = date.toLocaleString(DateTime.DATETIME_SHORT);
const relativeTime = formatRelativeTime(info.getValue());
diff --git a/client/src/app/admin/components/shared/GrowthChart.tsx b/client/src/app/admin/components/shared/GrowthChart.tsx
index 565514ebd..0c92bbab1 100644
--- a/client/src/app/admin/components/shared/GrowthChart.tsx
+++ b/client/src/app/admin/components/shared/GrowthChart.tsx
@@ -115,7 +115,6 @@ export function GrowthChart({ data, color = "#3b82f6", title }: GrowthChartProps
enableArea={false}
sliceTooltip={({ slice }: any) => {
const point = slice.points[0];
- const currentTime = DateTime.fromSQL(point.data.x as string);
return (
<ChartTooltip>
diff --git a/client/src/app/settings/organization/members/page.tsx b/client/src/app/settings/organization/members/page.tsx
index 1d302ed4e..1aabbfe91 100644
--- a/client/src/app/settings/organization/members/page.tsx
+++ b/client/src/app/settings/organization/members/page.tsx
@@ -1,5 +1,6 @@
"use client";
import { DateTime } from "luxon";
+import { getTimezone } from "../../../../lib/store";
import { Card, CardContent, CardHeader, CardTitle } from "../../../../components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../components/ui/table";
import { authClient } from "../../../../lib/auth";
@@ -194,7 +195,7 @@ function Organization({
<TableCell className="capitalize">{member.role}</TableCell>
<TableCell>
{DateTime.fromSQL(member.createdAt, { zone: "utc" })
- .toLocal()
+ .setZone(getTimezone())
.toLocaleString(DateTime.DATE_SHORT)}
</TableCell>
{isAdmin && (
diff --git a/client/src/app/uptime/incidents/page.tsx b/client/src/app/uptime/incidents/page.tsx
index f5e63014b..c18474fe0 100644
--- a/client/src/app/uptime/incidents/page.tsx
+++ b/client/src/app/uptime/incidents/page.tsx
@@ -10,6 +10,7 @@ import {
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { getTimezone } from "@/lib/store";
import { cn } from "@/lib/utils";
import { AlertCircle, CheckCircle, MoreHorizontal } from "lucide-react";
import { DateTime } from "luxon";
@@ -23,7 +24,7 @@ import {
} from "../../../api/uptime/incidents";
const formatStartTime = (timestamp: string) => {
- const dt = DateTime.fromSQL(timestamp, { zone: "UTC" }).toLocal();
+ const dt = DateTime.fromSQL(timestamp, { zone: "UTC" }).setZone(getTimezone());
return dt.toRelative() || dt.toFormat("MMM dd, HH:mm");
};
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx b/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
index 0be92b1dc..c9f3f76f5 100644
--- a/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
+++ b/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
@@ -9,6 +9,7 @@ import {
SortingState,
useReactTable,
} from "@tanstack/react-table";
+import { getTimezone } from "@/lib/store";
import { Loader2 } from "lucide-react";
import { DateTime } from "luxon";
import React, { useMemo, useState } from "react";
@@ -78,7 +79,7 @@ export function EventsTable({ monitor, monitorId }: { monitor?: UptimeMonitor; m
const timestamp = DateTime.fromSQL(row.original.timestamp, { zone: "utc" });
return (
<div className="text-sm">
- <div className="">{timestamp.toLocal().toFormat("MMM dd, HH:mm:ss")}</div>
+ <div className="">{timestamp.setZone(getTimezone()).toFormat("MMM dd, HH:mm:ss")}</div>
</div>
);
},
diff --git a/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx b/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx
index 52d29c759..a07ccd8a9 100644
--- a/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx
+++ b/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx
@@ -5,6 +5,7 @@ import { ChartTooltip } from "@/components/charts/ChartTooltip";
import { Card, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { formatChartDateTime, hour12, userLocale } from "@/lib/dateTimeUtils";
+import { getTimezone } from "@/lib/store";
import { cn } from "@/lib/utils";
import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
@@ -74,17 +75,20 @@ export function MonitorResponseTimeChart({
});
};
+ const timezone = getTimezone();
+
// Process data for the chart
const processedData =
statsData?.distribution
?.map((item: any) => {
if (!item.hour) return null;
- const timestamp = DateTime.fromSQL(item.hour, { zone: "utc" }).toLocal();
+ // Parse timestamp as UTC and keep in UTC for chart (useUTC: true)
+ const timestamp = DateTime.fromSQL(item.hour, { zone: "utc" });
if (!timestamp.isValid) return null;
const dataPoint: any = {
- time: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
+ time: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"), // UTC format for chart
timestamp: timestamp.toISO(), // Store ISO timestamp for proper timezone handling
response_time_ms: item.avg_response_time,
check_count: item.check_count || 0,
@@ -184,7 +188,8 @@ export function MonitorResponseTimeChart({
: [];
const formatXAxisValue = (value: Date) => {
- const dt = DateTime.fromJSDate(value).setLocale(userLocale);
+ // Interpret JS Date as UTC, then convert to selected timezone
+ const dt = DateTime.fromJSDate(value, { zone: "utc" }).setZone(timezone).setLocale(userLocale);
// Format based on bucket size
switch (bucket) {
@@ -275,7 +280,7 @@ export function MonitorResponseTimeChart({
type: "time",
precision: "second",
format: "%Y-%m-%d %H:%M:%S",
- useUTC: false,
+ useUTC: true,
}}
yScale={{
type: "linear",
@@ -362,11 +367,11 @@ export function MonitorResponseTimeChart({
"legends",
]}
sliceTooltip={({ slice }: any) => {
- const currentTime = DateTime.fromJSDate(new Date(slice.points[0].data.x));
+ const currentTime = DateTime.fromJSDate(new Date(slice.points[0].data.x), { zone: "utc" }).setZone(timezone);
// Find the corresponding data point to get failure info
const dataPoint = processedData.find(
- (p: any) => DateTime.fromISO(p.timestamp).toMillis() === currentTime.toMillis()
+ (p: any) => DateTime.fromISO(p.timestamp).toMillis() === currentTime.toUTC().toMillis()
);
// For stacked HTTP charts, show cumulative total
diff --git a/client/src/app/uptime/monitors/components/MonitorTableRow.tsx b/client/src/app/uptime/monitors/components/MonitorTableRow.tsx
index 1a8b0b864..fae69f928 100644
--- a/client/src/app/uptime/monitors/components/MonitorTableRow.tsx
+++ b/client/src/app/uptime/monitors/components/MonitorTableRow.tsx
@@ -1,6 +1,7 @@
import React from "react";
import { DateTime } from "luxon";
import { TableCell, TableRow } from "@/components/ui/table";
+import { getTimezone } from "@/lib/store";
import { StatusOrb } from "./StatusOrb";
import { UptimeBar } from "./UptimeBar";
import { UptimeMonitor, useMonitorUptime } from "@/api/uptime/monitors";
@@ -27,7 +28,7 @@ const formatLastPing = (lastCheckedAt?: string) => {
const lastPing = DateTime.fromSQL(lastCheckedAt, {
zone: "utc",
- }).toLocal();
+ }).setZone(getTimezone());
const now = DateTime.now();
const diffMs = now.toMillis() - lastPing.toMillis();
diff --git a/client/src/app/uptime/monitors/components/MonitorsTable.tsx b/client/src/app/uptime/monitors/components/MonitorsTable.tsx
index efc1570fd..a562ca324 100644
--- a/client/src/app/uptime/monitors/components/MonitorsTable.tsx
+++ b/client/src/app/uptime/monitors/components/MonitorsTable.tsx
@@ -14,6 +14,7 @@ import {
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { UptimeMonitor, useMonitors } from "@/api/uptime/monitors";
import { Skeleton } from "@/components/ui/skeleton";
+import { getTimezone } from "@/lib/store";
import { Radio, ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";
import { StatusOrb } from "./StatusOrb";
import { UptimeBar } from "./UptimeBar";
@@ -50,7 +51,7 @@ const formatLastPing = (lastCheckedAt?: string) => {
const lastPing = DateTime.fromSQL(lastCheckedAt, {
zone: "utc",
- }).toLocal();
+ }).setZone(getTimezone());
const now = DateTime.now();
const diffMs = now.toMillis() - lastPing.toMillis();
diff --git a/client/src/app/uptime/monitors/components/UptimeBar.tsx b/client/src/app/uptime/monitors/components/UptimeBar.tsx
index e355fe245..7f044f7cc 100644
--- a/client/src/app/uptime/monitors/components/UptimeBar.tsx
+++ b/client/src/app/uptime/monitors/components/UptimeBar.tsx
@@ -1,5 +1,6 @@
import React from "react";
import { cn } from "@/lib/utils";
+import { getTimezone } from "@/lib/store";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { DateTime } from "luxon";
import { useMonitorUptimeBuckets } from "@/api/uptime/monitors";
@@ -30,7 +31,7 @@ export function UptimeBar({ monitorId, className }: UptimeBarProps) {
}
// Process bucket data
const days = data.buckets.map(bucket => {
- const date = DateTime.fromSQL(bucket.bucket_time).toLocal();
+ const date = DateTime.fromSQL(bucket.bucket_time).setZone(getTimezone());
return {
date: bucket.bucket_formatted,
dateFormatted: date.toFormat("MMM dd"),
diff --git a/client/src/components/Avatar.tsx b/client/src/components/Avatar.tsx
index ee53b4d9f..2ac539fc8 100644
--- a/client/src/components/Avatar.tsx
+++ b/client/src/components/Avatar.tsx
@@ -1,6 +1,7 @@
import BoringAvatar from "boring-avatars";
import { DateTime } from "luxon";
import { animals, colors, uniqueNamesGenerator } from "unique-names-generator";
+import { getTimezone } from "../lib/store";
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
export const AVATAR_COLORS = [
@@ -27,7 +28,7 @@ export const AVATAR_COLORS = [
];
export function Avatar({ id, size = 20, lastActiveTime }: { id: string; size?: number; lastActiveTime?: DateTime }) {
- const timeSinceEnd = lastActiveTime ? -lastActiveTime.toLocal().diffNow().toMillis() / 1000 : 0;
+ const timeSinceEnd = lastActiveTime ? -lastActiveTime.setZone(getTimezone()).diffNow().toMillis() / 1000 : 0;
const online = lastActiveTime ? timeSinceEnd < 300 : false;
return (
<div className="relative">
diff --git a/client/src/components/DateSelector/DateSelector.tsx b/client/src/components/DateSelector/DateSelector.tsx
index 765c9c8bb..75bfe4d7f 100644
--- a/client/src/components/DateSelector/DateSelector.tsx
+++ b/client/src/components/DateSelector/DateSelector.tsx
@@ -11,7 +11,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { getTimezoneLabel, timezones } from "@/lib/dateTimeUtils";
-import { useStore } from "@/lib/store";
+import { getTimezone, getTodayInTimezone, useStore } from "@/lib/store";
import { Calendar, Check, Globe } from "lucide-react";
import { DateTime } from "luxon";
import { CustomDateRangePicker } from "./CustomDateRangePicker";
@@ -44,6 +44,10 @@ const getLabel = (time: Time) => {
return wellKnownLabels[time.wellKnown];
}
+ // Use timezone-aware "now" for comparisons
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
+
if (time.mode === "range") {
const startFormatted = DateTime.fromISO(time.startDate).toFormat("EEEE, MMM d");
const endFormatted = DateTime.fromISO(time.endDate).toFormat("EEEE, MMM d");
@@ -59,19 +63,19 @@ const getLabel = (time: Time) => {
}
if (time.mode === "day") {
- if (time.day === DateTime.now().toISODate()) {
+ if (time.day === now.toISODate()) {
return "Today";
}
- if (time.day === DateTime.now().minus({ days: 1 }).toISODate()) {
+ if (time.day === now.minus({ days: 1 }).toISODate()) {
return "Yesterday";
}
return DateTime.fromISO(time.day).toFormat("EEEE, MMM d");
}
if (time.mode === "week") {
- if (time.week === DateTime.now().startOf("week").toISODate()) {
+ if (time.week === now.startOf("week").toISODate()) {
return "This Week";
}
- if (time.week === DateTime.now().minus({ weeks: 1 }).startOf("week").toISODate()) {
+ if (time.week === now.minus({ weeks: 1 }).startOf("week").toISODate()) {
return "Last Week";
}
const startDate = DateTime.fromISO(time.week).toFormat("EEEE, MMM d");
@@ -79,16 +83,16 @@ const getLabel = (time: Time) => {
return `${startDate} - ${endDate}`;
}
if (time.mode === "month") {
- if (time.month === DateTime.now().startOf("month").toISODate()) {
+ if (time.month === now.startOf("month").toISODate()) {
return "This Month";
}
- if (time.month === DateTime.now().minus({ months: 1 }).startOf("month").toISODate()) {
+ if (time.month === now.minus({ months: 1 }).startOf("month").toISODate()) {
return "Last Month";
}
return DateTime.fromISO(time.month).toFormat("MMMM yyyy");
}
if (time.mode === "year") {
- if (time.year === DateTime.now().startOf("year").toISODate()) {
+ if (time.year === now.startOf("year").toISODate()) {
return "This Year";
}
return DateTime.fromISO(time.year).toFormat("yyyy");
@@ -117,79 +121,91 @@ export function DateSelector({
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
setTime({
mode: "day",
- day: DateTime.now().toISODate(),
+ day: now.toISODate()!,
wellKnown: "today",
- })
- }
+ });
+ }}
className="w-48"
>
<div className="w-4">{time.wellKnown === "today" && <Check className="w-4 h-4" />}</div>
Today
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
setTime({
mode: "range",
- startDate: DateTime.now().minus({ days: 2 }).toISODate(),
- endDate: DateTime.now().toISODate(),
+ startDate: now.minus({ days: 2 }).toISODate()!,
+ endDate: now.toISODate()!,
wellKnown: "last-3-days",
- })
- }
+ });
+ }}
>
<div className="w-4">{time.wellKnown === "last-3-days" && <Check className="w-4 h-4" />}</div>
Last 3 Days
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
setTime({
mode: "range",
- startDate: DateTime.now().minus({ days: 6 }).toISODate(),
- endDate: DateTime.now().toISODate(),
+ startDate: now.minus({ days: 6 }).toISODate()!,
+ endDate: now.toISODate()!,
wellKnown: "last-7-days",
- })
- }
+ });
+ }}
>
<div className="w-4">{time.wellKnown === "last-7-days" && <Check className="w-4 h-4" />}</div>
Last 7 Days
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
setTime({
mode: "range",
- startDate: DateTime.now().minus({ days: 13 }).toISODate(),
- endDate: DateTime.now().toISODate(),
+ startDate: now.minus({ days: 13 }).toISODate()!,
+ endDate: now.toISODate()!,
wellKnown: "last-14-days",
- })
- }
+ });
+ }}
>
<div className="w-4">{time.wellKnown === "last-14-days" && <Check className="w-4 h-4" />}</div>
Last 14 Days
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
setTime({
mode: "range",
- startDate: DateTime.now().minus({ days: 29 }).toISODate(),
- endDate: DateTime.now().toISODate(),
+ startDate: now.minus({ days: 29 }).toISODate()!,
+ endDate: now.toISODate()!,
wellKnown: "last-30-days",
- })
- }
+ });
+ }}
>
<div className="w-4">{time.wellKnown === "last-30-days" && <Check className="w-4 h-4" />}</div>
Last 30 Days
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
setTime({
mode: "range",
- startDate: DateTime.now().minus({ days: 59 }).toISODate(),
- endDate: DateTime.now().toISODate(),
+ startDate: now.minus({ days: 59 }).toISODate()!,
+ endDate: now.toISODate()!,
wellKnown: "last-60-days",
- })
- }
+ });
+ }}
>
<div className="w-4">{time.wellKnown === "last-60-days" && <Check className="w-4 h-4" />}</div>
Last 60 Days
@@ -253,37 +269,43 @@ export function DateSelector({
)}
<DropdownMenuSeparator />
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
setTime({
mode: "week",
- week: DateTime.now().startOf("week").toISODate(),
+ week: now.startOf("week").toISODate()!,
wellKnown: "this-week",
- })
- }
+ });
+ }}
>
<div className="w-4">{time.wellKnown === "this-week" && <Check className="w-4 h-4" />}</div>
This Week
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
setTime({
mode: "month",
- month: DateTime.now().startOf("month").toISODate(),
+ month: now.startOf("month").toISODate()!,
wellKnown: "this-month",
- })
- }
+ });
+ }}
>
<div className="w-4">{time.wellKnown === "this-month" && <Check className="w-4 h-4" />}</div>
This Month
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() =>
+ onClick={() => {
+ const tz = getTimezone();
+ const now = DateTime.now().setZone(tz);
setTime({
mode: "year",
- year: DateTime.now().startOf("year").toISODate(),
+ year: now.startOf("year").toISODate()!,
wellKnown: "this-year",
- })
- }
+ });
+ }}
>
<div className="w-4">{time.wellKnown === "this-year" && <Check className="w-4 h-4" />}</div>
This Year
diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsx
index bd5441da3..7c2ced1f9 100644
--- a/client/src/components/Sessions/SessionCard.tsx
+++ b/client/src/components/Sessions/SessionCard.tsx
@@ -1,5 +1,6 @@
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { getTimezone } from "@/lib/store";
import { ArrowRight, ChevronDown, ChevronRight, Video } from "lucide-react";
import { DateTime } from "luxon";
import { memo, useState } from "react";
@@ -159,7 +160,7 @@ export function SessionCard({ session, onClick, userId, expandedByDefault }: Ses
zone: "utc",
})
.setLocale(userLocale)
- .toLocal()
+ .setZone(getTimezone())
.toFormat(hour12 ? "MMM d, h:mm a" : "dd MMM, HH:mm")}
</span>
<span className="text-neutral-500 dark:text-neutral-400">•</span>
diff --git a/client/src/components/Sessions/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails.tsx
index 1309de1e7..9a146c2ee 100644
--- a/client/src/components/Sessions/SessionDetails.tsx
+++ b/client/src/components/Sessions/SessionDetails.tsx
@@ -4,6 +4,7 @@ import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { getTimezone } from "@/lib/store";
import { ArrowRight, Clock, ExternalLink, Loader2, Monitor, Smartphone, Tablet, TriangleAlert } from "lucide-react";
import { DateTime } from "luxon";
import Link from "next/link";
@@ -38,13 +39,13 @@ function PageviewItem({
const isEvent = item.type === "custom_event";
const isPageview = item.type === "pageview";
const isOutbound = item.type === "outbound";
- const timestamp = DateTime.fromSQL(item.timestamp, { zone: "utc" }).toLocal();
+ const timestamp = DateTime.fromSQL(item.timestamp, { zone: "utc" }).setZone(getTimezone());
const formattedTime = timestamp.toFormat(hour12 ? "h:mm:ss a" : "HH:mm:ss");
// Calculate duration if this is a pageview and we have the next timestamp
let duration = null;
if (isPageview && nextTimestamp) {
- const nextTime = DateTime.fromSQL(nextTimestamp, { zone: "utc" }).toLocal();
+ const nextTime = DateTime.fromSQL(nextTimestamp, { zone: "utc" }).setZone(getTimezone());
const totalSeconds = Math.floor(nextTime.diff(timestamp).milliseconds / 1000);
duration = formatDuration(totalSeconds);
}
diff --git a/client/src/components/replay/ReplayBreadcrumbs.tsx b/client/src/components/replay/ReplayBreadcrumbs.tsx
index c99c5533e..fa055bc53 100644
--- a/client/src/components/replay/ReplayBreadcrumbs.tsx
+++ b/client/src/components/replay/ReplayBreadcrumbs.tsx
@@ -33,6 +33,7 @@ import { Avatar } from "@/components/Avatar";
import { IdentifiedBadge } from "@/components/IdentifiedBadge";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { getTimezone } from "@/lib/store";
import { cn, getUserDisplayName } from "@/lib/utils";
import { useReplayStore } from "./replayStore";
@@ -268,7 +269,7 @@ export function ReplayBreadcrumbs() {
id={data.metadata.user_id}
size={24}
lastActiveTime={
- data.metadata.end_time ? DateTime.fromSQL(data.metadata.end_time, { zone: "utc" }).toLocal() : undefined
+ data.metadata.end_time ? DateTime.fromSQL(data.metadata.end_time, { zone: "utc" }).setZone(getTimezone()) : undefined
}
/>
<span className="truncate max-w-[120px]">{getUserDisplayName(data.metadata)}</span>
diff --git a/client/src/lib/dateTimeUtils.ts b/client/src/lib/dateTimeUtils.ts
index b60009e28..08bf77588 100644
--- a/client/src/lib/dateTimeUtils.ts
+++ b/client/src/lib/dateTimeUtils.ts
@@ -1,5 +1,6 @@
import { TimeBucket } from "@rybbit/shared";
import { DateTime, Duration, DurationLikeObject, Settings } from "luxon";
+import { getTimezone } from "./store";
// Detect user locale from the browser environment (fallback to 'en-US' on server)
export const userLocale = typeof navigator !== "undefined" ? navigator.language : "en-US";
@@ -161,6 +162,7 @@ export const formatChartDateTime = (dt: DateTime, bucket: TimeBucket) => {
day: "numeric",
hour: "numeric",
hour12: hour12,
+ timeZone: getTimezone(),
};
if (showMinutes && !hour12) {
options.minute = "numeric";
@@ -178,12 +180,12 @@ export const formatChartDateTime = (dt: DateTime, bucket: TimeBucket) => {
};
/**
- * Converts a UTC timestamp string to local time for display
+ * Converts a UTC timestamp string to user's selected timezone for display
* @param timestamp - UTC timestamp string from the server
- * @returns DateTime object in local timezone
+ * @returns DateTime object in user's selected timezone
*/
export const parseUtcTimestamp = (timestamp: string): DateTime => {
- return DateTime.fromSQL(timestamp, { zone: "utc" }).toLocal();
+ return DateTime.fromSQL(timestamp, { zone: "utc" }).setZone(getTimezone());
};
// Timezones with GMT offset and city name
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index ac7d46bb7..5ab472de3 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -10,6 +10,111 @@ const getSystemTimezone = () =>
? Intl.DateTimeFormat().resolvedOptions().timeZone
: "UTC";
+// Get today's date string in a specific timezone
+export const getTodayInTimezone = (tz?: string): string => {
+ const timezone = tz ?? (typeof window !== "undefined" ? useStore.getState().timezone : "system");
+ const resolvedTz = timezone === "system" ? getSystemTimezone() : timezone;
+ return DateTime.now().setZone(resolvedTz).toISODate() ?? DateTime.now().toISODate()!;
+};
+
+// Get a date relative to today in a specific timezone
+export const getRelativeDateInTimezone = (days: number, tz?: string): string => {
+ const timezone = tz ?? (typeof window !== "undefined" ? useStore.getState().timezone : "system");
+ const resolvedTz = timezone === "system" ? getSystemTimezone() : timezone;
+ return DateTime.now().setZone(resolvedTz).plus({ days }).toISODate() ?? "";
+};
+
+// Recalculate time based on wellKnown value for a new timezone
+const recalculateTimeForTimezone = (time: Time, timezone: string): Time | null => {
+ if (!time.wellKnown) return null;
+
+ const now = DateTime.now().setZone(timezone);
+ const today = now.toISODate() ?? "";
+ const yesterday = now.minus({ days: 1 }).toISODate() ?? "";
+
+ switch (time.wellKnown) {
+ case "today":
+ return { mode: "day", day: today, wellKnown: "today" };
+ case "yesterday":
+ return { mode: "day", day: yesterday, wellKnown: "yesterday" };
+ case "last-3-days":
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 2 }).toISODate() ?? "",
+ endDate: today,
+ wellKnown: "last-3-days",
+ };
+ case "last-7-days":
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 6 }).toISODate() ?? "",
+ endDate: today,
+ wellKnown: "last-7-days",
+ };
+ case "last-14-days":
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 13 }).toISODate() ?? "",
+ endDate: today,
+ wellKnown: "last-14-days",
+ };
+ case "last-30-days":
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 29 }).toISODate() ?? "",
+ endDate: today,
+ wellKnown: "last-30-days",
+ };
+ case "last-60-days":
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 59 }).toISODate() ?? "",
+ endDate: today,
+ wellKnown: "last-60-days",
+ };
+ case "this-week":
+ return {
+ mode: "week",
+ week: now.startOf("week").toISODate() ?? "",
+ wellKnown: "this-week",
+ };
+ case "last-week":
+ return {
+ mode: "week",
+ week: now.minus({ weeks: 1 }).startOf("week").toISODate() ?? "",
+ wellKnown: "last-week",
+ };
+ case "this-month":
+ return {
+ mode: "month",
+ month: now.startOf("month").toISODate() ?? "",
+ wellKnown: "this-month",
+ };
+ case "last-month":
+ return {
+ mode: "month",
+ month: now.minus({ months: 1 }).startOf("month").toISODate() ?? "",
+ wellKnown: "last-month",
+ };
+ case "this-year":
+ return {
+ mode: "year",
+ year: now.startOf("year").toISODate() ?? "",
+ wellKnown: "this-year",
+ };
+ case "all-time":
+ return { mode: "all-time", wellKnown: "all-time" };
+ // past-minutes modes don't need date recalculation (they're relative to "now")
+ case "last-30-minutes":
+ case "last-1-hour":
+ case "last-6-hours":
+ case "last-24-hours":
+ return null;
+ default:
+ return null;
+ }
+};
+
export type StatType = "pageviews" | "sessions" | "users" | "pages_per_session" | "bounce_rate" | "session_duration";
type Store = {
@@ -32,7 +137,7 @@ type Store = {
export const useStore = create<Store>()(
persist(
- (set) => ({
+ (set, get) => ({
site: "",
setSite: (site) => {
// Get current URL search params to check for stored state
@@ -157,7 +262,20 @@ export const useStore = create<Store>()(
filters: [],
setFilters: (filters) => set({ filters }),
timezone: "system",
- setTimezone: (timezone) => set({ timezone }),
+ setTimezone: (newTimezone) => {
+ const state = get();
+ const resolvedTz = newTimezone === "system" ? getSystemTimezone() : newTimezone;
+ const newTime = recalculateTimeForTimezone(state.time, resolvedTz);
+
+ // If time should be recalculated (has wellKnown), update via setTime
+ if (newTime) {
+ set({ timezone: newTimezone });
+ // Use setTime to properly recalculate previousTime and bucket
+ get().setTime(newTime);
+ } else {
+ set({ timezone: newTimezone });
+ }
+ },
}),
{
name: "rybbit-store",
@@ -172,6 +290,11 @@ export const getTimezone = () => {
return timezone === "system" ? getSystemTimezone() : timezone;
};
+// Helper to convert a DateTime to the user's selected timezone
+export const toUserTimezone = (dt: DateTime): DateTime => {
+ return dt.setZone(getTimezone());
+};
+
export const resetStore = () => {
const { setSite, setTime, setBucket, setSelectedStat, setFilters } = useStore.getState();
setSite("");
diff --git a/client/src/lib/urlParams.ts b/client/src/lib/urlParams.ts
index 02b10c175..72189732f 100644
--- a/client/src/lib/urlParams.ts
+++ b/client/src/lib/urlParams.ts
@@ -6,59 +6,96 @@ import { useQueryStates } from "nuqs";
import React, { useEffect } from "react";
import { Time } from "../components/DateSelector/types";
import { analyticsParsers } from "./parsers";
-import { useStore } from "./store";
+import { getTimezone, useStore } from "./store";
// Map of wellKnown presets to their dynamic time calculations
+// Uses timezone-aware dates based on the user's selected timezone
const wellKnownPresets: Record<string, () => Time> = {
- today: () => ({ mode: "day", day: DateTime.now().toISODate(), wellKnown: "today" }),
- yesterday: () => ({ mode: "day", day: DateTime.now().minus({ days: 1 }).toISODate(), wellKnown: "yesterday" }),
- "last-3-days": () => ({
- mode: "range",
- startDate: DateTime.now().minus({ days: 2 }).toISODate(),
- endDate: DateTime.now().toISODate(),
- wellKnown: "last-3-days",
- }),
- "last-7-days": () => ({
- mode: "range",
- startDate: DateTime.now().minus({ days: 6 }).toISODate(),
- endDate: DateTime.now().toISODate(),
- wellKnown: "last-7-days",
- }),
- "last-14-days": () => ({
- mode: "range",
- startDate: DateTime.now().minus({ days: 13 }).toISODate(),
- endDate: DateTime.now().toISODate(),
- wellKnown: "last-14-days",
- }),
- "last-30-days": () => ({
- mode: "range",
- startDate: DateTime.now().minus({ days: 29 }).toISODate(),
- endDate: DateTime.now().toISODate(),
- wellKnown: "last-30-days",
- }),
- "last-60-days": () => ({
- mode: "range",
- startDate: DateTime.now().minus({ days: 59 }).toISODate(),
- endDate: DateTime.now().toISODate(),
- wellKnown: "last-60-days",
- }),
- "this-week": () => ({ mode: "week", week: DateTime.now().startOf("week").toISODate(), wellKnown: "this-week" }),
- "last-week": () => ({
- mode: "week",
- week: DateTime.now().minus({ weeks: 1 }).startOf("week").toISODate(),
- wellKnown: "last-week",
- }),
- "this-month": () => ({
- mode: "month",
- month: DateTime.now().startOf("month").toISODate(),
- wellKnown: "this-month",
- }),
- "last-month": () => ({
- mode: "month",
- month: DateTime.now().minus({ months: 1 }).startOf("month").toISODate(),
- wellKnown: "last-month",
- }),
- "this-year": () => ({ mode: "year", year: DateTime.now().startOf("year").toISODate(), wellKnown: "this-year" }),
+ today: () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return { mode: "day", day: now.toISODate()!, wellKnown: "today" };
+ },
+ yesterday: () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return { mode: "day", day: now.minus({ days: 1 }).toISODate()!, wellKnown: "yesterday" };
+ },
+ "last-3-days": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 2 }).toISODate()!,
+ endDate: now.toISODate()!,
+ wellKnown: "last-3-days",
+ };
+ },
+ "last-7-days": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 6 }).toISODate()!,
+ endDate: now.toISODate()!,
+ wellKnown: "last-7-days",
+ };
+ },
+ "last-14-days": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 13 }).toISODate()!,
+ endDate: now.toISODate()!,
+ wellKnown: "last-14-days",
+ };
+ },
+ "last-30-days": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 29 }).toISODate()!,
+ endDate: now.toISODate()!,
+ wellKnown: "last-30-days",
+ };
+ },
+ "last-60-days": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return {
+ mode: "range",
+ startDate: now.minus({ days: 59 }).toISODate()!,
+ endDate: now.toISODate()!,
+ wellKnown: "last-60-days",
+ };
+ },
+ "this-week": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return { mode: "week", week: now.startOf("week").toISODate()!, wellKnown: "this-week" };
+ },
+ "last-week": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return {
+ mode: "week",
+ week: now.minus({ weeks: 1 }).startOf("week").toISODate()!,
+ wellKnown: "last-week",
+ };
+ },
+ "this-month": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return {
+ mode: "month",
+ month: now.startOf("month").toISODate()!,
+ wellKnown: "this-month",
+ };
+ },
+ "last-month": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return {
+ mode: "month",
+ month: now.minus({ months: 1 }).startOf("month").toISODate()!,
+ wellKnown: "last-month",
+ };
+ },
+ "this-year": () => {
+ const now = DateTime.now().setZone(getTimezone());
+ return { mode: "year", year: now.startOf("year").toISODate()!, wellKnown: "this-year" };
+ },
"last-30-minutes": () => ({
mode: "past-minutes",
pastMinutesStart: 30,