Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Migrate the invite page to Intl datetime formatting (#2519)

Luke Vella5eec596908a0
diff --git a/apps/web/src/app/[locale]/(optional-space)/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/layout.tsx
index a76af4985..9aa585fcd 100644
--- a/apps/web/src/app/[locale]/(optional-space)/layout.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/layout.tsx
@@ -3,6 +3,8 @@ import { SessionRefresher } from "@/components/session-refresher";
import { PreferencesProvider } from "@/contexts/preferences";
import { PayWall } from "@/features/billing/components/pay-wall";
import { isQuickCreateEnabled } from "@/features/quick-create";
+import { DateTimeProvider } from "@/lib/datetime/client";
+import { getDeviceDateTimeConfig } from "@/lib/datetime/server";
import {
createPrivateSSRHelper,
createPublicSSRHelper,
@@ -17,17 +19,27 @@ export default async function Layout({
? await createPublicSSRHelper()
: await createPrivateSSRHelper();
- await Promise.all([
+ const [deviceDateTimeConfig, user] = await Promise.all([
+ getDeviceDateTimeConfig(),
+ helpers.user.getMe.fetch(),
helpers.billing.getTier.prefetch(),
- helpers.user.getMe.prefetch(),
]);
return (
<HydrationBoundary state={dehydrate(helpers.queryClient)}>
<SessionRefresher />
<PreferencesProvider>
- {children}
- <PayWall />
+ <DateTimeProvider
+ timeZone={
+ deviceDateTimeConfig.timeZone ?? user?.timeZone ?? undefined
+ }
+ timeFormat={
+ deviceDateTimeConfig.timeFormat ?? user?.timeFormat ?? undefined
+ }
+ >
+ {children}
+ <PayWall />
+ </DateTimeProvider>
</PreferencesProvider>
</HydrationBoundary>
);
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/page.tsx
index 89f944e13..08986c486 100644
--- a/apps/web/src/app/[locale]/invite/[urlId]/page.tsx
+++ b/apps/web/src/app/[locale]/invite/[urlId]/page.tsx
@@ -6,7 +6,9 @@ import { notFound } from "next/navigation";
import { cache } from "react";
import { SessionRefresher } from "@/components/session-refresher";
import { PermissionProvider } from "@/contexts/permissions";
-import { PreferencesProvider } from "@/contexts/preferences";
+import { DateTimeProvider } from "@/lib/datetime/client";
+import { getDeviceDateTimeConfig } from "@/lib/datetime/server";
+import { LocaleSync } from "@/lib/locale/client";
import { createPublicSSRHelper } from "@/trpc/server/create-ssr-helper";
import { decryptToken } from "@/utils/session";
import { InvitePageLoader } from "./invite-page-loader";
@@ -46,8 +48,9 @@ export default async function Page(props: {
const token = (await props.searchParams).token;
- await Promise.all([
- trpc.user.getMe.prefetch(),
+ const [user, deviceDateTimeConfig] = await Promise.all([
+ trpc.user.getMe.fetch(),
+ getDeviceDateTimeConfig(),
trpc.polls.get.prefetch({ urlId: params.urlId }),
trpc.polls.participants.list.prefetch({ pollId: params.urlId, token }),
trpc.polls.comments.list.prefetch({ pollId: params.urlId }),
@@ -64,13 +67,17 @@ export default async function Page(props: {
return (
<HydrationBoundary state={dehydrate(trpc.queryClient)}>
<SessionRefresher />
- <PreferencesProvider>
+ <LocaleSync userLocale={user?.locale ?? undefined} />
+ <DateTimeProvider
+ timeZone={deviceDateTimeConfig.timeZone}
+ timeFormat={deviceDateTimeConfig.timeFormat}
+ >
<Providers>
<PermissionProvider impersonatedUserId={impersonatedUserId}>
<InvitePageLoader />
</PermissionProvider>
</Providers>
- </PreferencesProvider>
+ </DateTimeProvider>
</HydrationBoundary>
);
}
diff --git a/apps/web/src/components/clock.tsx b/apps/web/src/components/clock.tsx
index c73cbfa9b..fbc97c3b9 100644
--- a/apps/web/src/components/clock.tsx
+++ b/apps/web/src/components/clock.tsx
@@ -11,21 +11,31 @@ import {
} from "@rallly/ui/dialog";
import { Label } from "@rallly/ui/label";
import { GlobeIcon } from "lucide-react";
+import { useRouter } from "next/navigation";
import React from "react";
import { useInterval } from "react-use";
-import spacetime from "spacetime";
-import soft from "timezone-soft";
import { TimeFormatPicker } from "@/components/time-format-picker";
import { TimeZoneSelect } from "@/components/time-zone-picker/time-zone-select";
import { getCityFromTimezoneId } from "@/components/time-zone-picker/timezone-data";
-import { usePreferences } from "@/contexts/preferences";
import { Trans } from "@/i18n/client";
-import { dayjs } from "@/lib/dayjs";
-import { useDayjs } from "@/utils/dayjs";
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import {
+ setDeviceTimeFormat,
+ setTimeZoneOverride,
+} from "@/lib/datetime/device";
+import { Time } from "@/lib/datetime/time";
const TimePreferences = () => {
- const { updatePreferences } = usePreferences();
- const { timeFormat, timeZone } = useDayjs();
+ const router = useRouter();
+ const { locale, timeZone, timeFormat } = useDateTimeConfig();
+
+ // When there's no explicit preference, show the locale's default format.
+ const resolvedTimeFormat =
+ timeFormat ??
+ (new Intl.DateTimeFormat(locale, { hour: "numeric" }).resolvedOptions()
+ .hour12
+ ? "hours12"
+ : "hours24");
return (
<div className="grid gap-4">
@@ -36,7 +46,8 @@ const TimePreferences = () => {
<TimeZoneSelect
value={timeZone}
onValueChange={(newTimeZone) => {
- updatePreferences({ timeZone: newTimeZone });
+ setTimeZoneOverride(newTimeZone);
+ router.refresh();
}}
/>
</div>
@@ -45,9 +56,10 @@ const TimePreferences = () => {
<Trans i18nKey="timeFormat" />
</Label>
<TimeFormatPicker
- value={timeFormat}
+ value={resolvedTimeFormat}
onChange={(newTimeFormat) => {
- updatePreferences({ timeFormat: newTimeFormat });
+ setDeviceTimeFormat(newTimeFormat);
+ router.refresh();
}}
/>
</div>
@@ -56,22 +68,18 @@ const TimePreferences = () => {
};
const Clock = ({ className }: { className?: string }) => {
- const { timeZone, timeFormat } = useDayjs();
- const timeZoneDisplayFormat = soft(timeZone)[0];
- const now = spacetime.now(timeZone);
- const standardAbbrev = timeZoneDisplayFormat.standard.abbr;
- const dstAbbrev = timeZoneDisplayFormat.daylight?.abbr;
- const abbrev = now.isDST() ? dstAbbrev : standardAbbrev;
- const [time, setTime] = React.useState(new Date());
+ const [time, setTime] = React.useState(() => new Date());
useInterval(() => {
setTime(new Date());
}, 1000);
return (
- <span
- key={timeFormat}
+ <Time
+ value={time}
+ preset="time"
+ showTimeZone
className={cn("inline-block font-medium tabular-nums", className)}
- >{`${dayjs(time).tz(timeZone).format("LT")} ${abbrev}`}</span>
+ />
);
};
@@ -101,7 +109,12 @@ const ClockPreferences = ({ children }: React.PropsWithChildren) => {
};
export const TimesShownIn = () => {
- const { timeZone } = useDayjs();
+ const { timeZone } = useDateTimeConfig();
+
+ if (!timeZone) {
+ return null;
+ }
+
return (
<ClockPreferences>
<Button type="button" variant="ghost">
diff --git a/apps/web/src/components/discussion/discussion.tsx b/apps/web/src/components/discussion/discussion.tsx
index 63ea1c0e0..8690ec030 100644
--- a/apps/web/src/components/discussion/discussion.tsx
+++ b/apps/web/src/components/discussion/discussion.tsx
@@ -28,7 +28,7 @@ import { useEditToken } from "@/components/poll/mutations";
import { usePoll } from "@/contexts/poll";
import { useRole } from "@/contexts/role";
import { Trans, useTranslation } from "@/i18n/client";
-import { dayjs } from "@/lib/dayjs";
+import { RelativeTime } from "@/lib/datetime/relative-time";
import { trpc } from "@/trpc/client";
import { requiredString } from "../../utils/form-validation";
import TruncatedLinkify from "../poll/truncated-linkify";
@@ -201,7 +201,7 @@ function DiscussionInner() {
</Participant>
<div className="flex items-center gap-2 text-sm">
<div className="text-muted-foreground">
- {dayjs(comment.createdAt).fromNow()}
+ <RelativeTime value={comment.createdAt} />
</div>
{canDelete && (
<DropdownMenu>
diff --git a/apps/web/src/components/new-participant-modal.tsx b/apps/web/src/components/new-participant-modal.tsx
index 7e8f4be94..f0860fbd5 100644
--- a/apps/web/src/components/new-participant-modal.tsx
+++ b/apps/web/src/components/new-participant-modal.tsx
@@ -18,7 +18,7 @@ import { useForm } from "react-hook-form";
import * as z from "zod";
import { usePoll } from "@/contexts/poll";
import { useTranslation } from "@/i18n/client";
-import { useDayjs } from "@/utils/dayjs";
+import { useDateTimeConfig } from "@/lib/datetime/client";
import { useAddParticipantMutation } from "./poll/mutations";
import VoteIcon from "./poll/vote-icon";
import { useUser } from "./user-provider";
@@ -91,7 +91,7 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {
const poll = usePoll();
const isEmailRequired = poll.requireParticipantEmail;
- const { timeZone } = useDayjs();
+ const { timeZone } = useDateTimeConfig();
const { user, createGuestIfNeeded } = useUser();
const isLoggedIn = user && !user.isGuest;
const form = useForm({
diff --git a/apps/web/src/components/poll-context.test.ts b/apps/web/src/components/poll-context.test.ts
index c64d98378..5a6ed2963 100644
--- a/apps/web/src/components/poll-context.test.ts
+++ b/apps/web/src/components/poll-context.test.ts
@@ -18,12 +18,13 @@ describe("createOptionsContextValue — all-day options are timezone-invariant",
["Europe/Berlin", "America/Los_Angeles"], // viewer far ahead of source
["Asia/Tokyo", "Europe/Berlin"],
["UTC", "Europe/Berlin"],
- ])("renders Jul 1 for target=%s, source=%s", (targetTimeZone, sourceTimeZone) => {
- const result = createOptionsContextValue(
- [allDayOption],
- targetTimeZone,
- sourceTimeZone,
- );
+ ])("renders Jul 1 for viewer=%s, poll=%s", (timeZone, pollTimeZone) => {
+ const result = createOptionsContextValue({
+ pollOptions: [allDayOption],
+ pollTimeZone,
+ locale: "en",
+ timeZone,
+ });
expect(result.pollType).toBe("date");
expect(result.options[0]).toMatchObject({
@@ -35,12 +36,57 @@ describe("createOptionsContextValue — all-day options are timezone-invariant",
});
it("does not shift when the poll has no timezone", () => {
- const result = createOptionsContextValue(
- [allDayOption],
- "America/Los_Angeles",
- null,
- );
+ const result = createOptionsContextValue({
+ pollOptions: [allDayOption],
+ pollTimeZone: null,
+ locale: "en",
+ timeZone: "America/Los_Angeles",
+ });
expect(result.options[0]).toMatchObject({ day: "1", month: "Jul" });
});
});
+
+describe("createOptionsContextValue — time slots", () => {
+ const timeSlotOption = {
+ id: "opt-1",
+ startTime: new Date("2026-07-01T18:00:00Z"),
+ duration: 60,
+ };
+
+ it("shows fixed times in the viewer's zone", () => {
+ const result = createOptionsContextValue({
+ pollOptions: [timeSlotOption],
+ pollTimeZone: "Europe/London",
+ locale: "en",
+ timeZone: "America/New_York",
+ timeFormat: "hours12",
+ });
+
+ expect(result.pollType).toBe("timeSlot");
+ expect(result.options[0]).toMatchObject({
+ type: "timeSlot",
+ startTime: "2:00 PM",
+ endTime: "3:00 PM",
+ day: "1",
+ dow: "Wed",
+ month: "Jul",
+ year: "2026",
+ });
+ });
+
+ it("shows floating times as stored, ignoring the viewer's zone", () => {
+ const result = createOptionsContextValue({
+ pollOptions: [timeSlotOption],
+ pollTimeZone: null,
+ locale: "en",
+ timeZone: "America/New_York",
+ timeFormat: "hours24",
+ });
+
+ expect(result.options[0]).toMatchObject({
+ startTime: "18:00",
+ endTime: "19:00",
+ });
+ });
+});
diff --git a/apps/web/src/components/poll-context.tsx b/apps/web/src/components/poll-context.tsx
index cbbaef420..942e138d6 100644
--- a/apps/web/src/components/poll-context.tsx
+++ b/apps/web/src/components/poll-context.tsx
@@ -1,15 +1,15 @@
-import type { VoteType } from "@rallly/database";
+import type { TimeFormat, VoteType } from "@rallly/database";
import { TrashIcon } from "lucide-react";
import React from "react";
import { useTranslation } from "@/i18n/client";
-import { dayjs } from "@/lib/dayjs";
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import { formatDateParts, formatDateTime } from "@/lib/datetime/format";
import type { GetPollApiResponse } from "@/trpc/client/types";
import type {
ParsedDateOption,
ParsedTimeSlotOption,
} from "@/utils/date-time-utils";
-import { getDuration } from "@/utils/date-time-utils";
-import { useDayjs } from "@/utils/dayjs";
+import { formatDuration } from "@/utils/date-time-utils";
import { useParticipants } from "./participants-provider";
import { useRequiredContext } from "./use-required-context";
@@ -130,11 +130,24 @@ export const useOptions = () => {
return context;
};
-export function createOptionsContextValue(
- pollOptions: { id: string; startTime: Date; duration: number }[],
- targetTimeZone: string,
- sourceTimeZone: string | null,
-): OptionsContextValue {
+export function createOptionsContextValue({
+ pollOptions,
+ pollTimeZone,
+ locale,
+ timeZone,
+ timeFormat,
+}: {
+ pollOptions: { id: string; startTime: Date; duration: number }[];
+ /**
+ * The poll's zone: set means options are fixed instants shown in the
+ * viewer's zone; null means floating times shown as stored.
+ */
+ pollTimeZone: string | null;
+ locale: string;
+ /** The viewer's zone; undefined falls back to the system zone. */
+ timeZone?: string;
+ timeFormat?: TimeFormat;
+}): OptionsContextValue {
if (pollOptions.length === 0) {
return {
pollType: "date",
@@ -142,32 +155,40 @@ export function createOptionsContextValue(
};
}
if (pollOptions[0].duration > 0) {
+ // Floating times are stored as UTC wall times, so reading them in UTC
+ // shows them unshifted.
+ const displayTimeZone = pollTimeZone ? timeZone : "UTC";
return {
pollType: "timeSlot",
options: pollOptions.map((option) => {
- function adjustTimeZone(date: Date) {
- if (sourceTimeZone) {
- return dayjs(date).tz(targetTimeZone);
- }
- return dayjs(date).utc();
- }
- const localStartTime = adjustTimeZone(option.startTime);
-
- // for some reason, dayjs requires us to do timezone conversion at the end
- const localEndTime = adjustTimeZone(
- dayjs(option.startTime).add(option.duration, "minute").toDate(),
+ const endTime = new Date(
+ option.startTime.getTime() + option.duration * 60_000,
);
+ const parts = formatDateParts(option.startTime, {
+ locale,
+ timeZone: displayTimeZone,
+ });
return {
optionId: option.id,
type: "timeSlot",
- startTime: localStartTime.format("LT"),
- endTime: localEndTime.format("LT"),
- duration: getDuration(localStartTime, localEndTime),
- month: localStartTime.format("MMM"),
- day: localStartTime.format("D"),
- dow: localStartTime.format("ddd"),
- year: localStartTime.format("YYYY"),
+ startTime: formatDateTime(option.startTime, {
+ preset: "time",
+ locale,
+ timeFormat,
+ timeZone: displayTimeZone,
+ }),
+ endTime: formatDateTime(endTime, {
+ preset: "time",
+ locale,
+ timeFormat,
+ timeZone: displayTimeZone,
+ }),
+ duration: formatDuration(option.duration, locale),
+ month: parts.month,
+ day: parts.day,
+ dow: parts.weekday,
+ year: parts.year,
} satisfies ParsedTimeSlotOption;
}),
};
@@ -177,15 +198,18 @@ export function createOptionsContextValue(
options: pollOptions.map((option) => {
// All-day options are floating dates: always read them in UTC so the
// calendar date is identical for every viewer, regardless of timezone.
- const localTime = dayjs(option.startTime).utc();
+ const parts = formatDateParts(option.startTime, {
+ locale,
+ timeZone: "UTC",
+ });
return {
optionId: option.id,
type: "date",
- month: localTime.format("MMM"),
- day: localTime.format("D"),
- dow: localTime.format("ddd"),
- year: localTime.format("YYYY"),
+ month: parts.month,
+ day: parts.day,
+ dow: parts.weekday,
+ year: parts.year,
} satisfies ParsedDateOption;
}),
};
@@ -194,16 +218,17 @@ export function createOptionsContextValue(
export const OptionsProvider = (props: React.PropsWithChildren) => {
const { poll } = usePoll();
- const { timeZone: targetTimeZone, timeFormat } = useDayjs();
+ const { locale, timeZone, timeFormat } = useDateTimeConfig();
- // biome-ignore lint/correctness/useExhaustiveDependencies: Fix this later
const options = React.useMemo(() => {
- return createOptionsContextValue(
- poll.options,
- targetTimeZone,
- poll.timeZone,
- );
- }, [poll.options, poll.timeZone, targetTimeZone, timeFormat]);
+ return createOptionsContextValue({
+ pollOptions: poll.options,
+ pollTimeZone: poll.timeZone,
+ locale,
+ timeZone,
+ timeFormat,
+ });
+ }, [poll.options, poll.timeZone, locale, timeZone, timeFormat]);
return (
<OptionsContext.Provider value={options}>
diff --git a/apps/web/src/components/poll/responsive-results.tsx b/apps/web/src/components/poll/responsive-results.tsx
index f5c33339f..bd3a78f68 100644
--- a/apps/web/src/components/poll/responsive-results.tsx
+++ b/apps/web/src/components/poll/responsive-results.tsx
@@ -17,9 +17,11 @@ import {
import DesktopPoll from "@/components/poll/desktop-poll";
import MobilePoll from "@/components/poll/mobile-poll";
import { usePoll } from "@/contexts/poll";
+import {
+ EventDate,
+ EventTimeRange,
+} from "@/features/scheduled-event/components/event-date-time";
import { Trans } from "@/i18n/client";
-import { dayjs } from "@/lib/dayjs";
-import { useDayjs } from "@/utils/dayjs";
const useBreakpoint = createBreakpoint({ list: 320, table: 640 });
@@ -32,31 +34,24 @@ function ScheduledDateTime({
duration: number;
timeZone: string | null;
}) {
- const { adjustTimeZone } = useDayjs();
- const adjusted = adjustTimeZone(start, !timeZone);
- const date = adjusted.format("dddd, LL");
-
- if (duration === 0) {
- return (
- <span className="flex flex-col items-center gap-0.5">
- <span>{date}</span>
- <span>
- <Trans i18nKey="allDay" />
- </span>
- </span>
- );
- }
-
- const endTime = adjustTimeZone(
- dayjs(start).add(duration, "minutes"),
- !timeZone,
- );
- const time = `${adjusted.format("LT")} - ${endTime.format(timeZone ? "LT z" : "LT")}`;
+ const allDay = duration === 0;
return (
<span className="flex flex-col items-center gap-0.5">
- <span className="text-foreground">{date}</span>
- <span>{time}</span>
+ <EventDate
+ value={start}
+ allDay={allDay}
+ timeZone={timeZone}
+ preset="dateFull"
+ className={allDay ? undefined : "text-foreground"}
+ />
+ <EventTimeRange
+ start={start}
+ end={new Date(start.getTime() + duration * 60_000)}
+ allDay={allDay}
+ timeZone={timeZone}
+ showTimeZone
+ />
</span>
);
}
diff --git a/apps/web/src/features/scheduled-event/components/event-date-time.tsx b/apps/web/src/features/scheduled-event/components/event-date-time.tsx
index 02e998fe7..cc77a3f4e 100644
--- a/apps/web/src/features/scheduled-event/components/event-date-time.tsx
+++ b/apps/web/src/features/scheduled-event/components/event-date-time.tsx
@@ -49,10 +49,13 @@ export function EventTimeRange({
end,
allDay,
timeZone,
+ showTimeZone,
className,
}: SchedulingFields & {
start: DateInput;
end: DateInput;
+ /** Show the zone label on fixed times; floating times never show one. */
+ showTimeZone?: boolean;
className?: string;
}) {
if (allDay) {
@@ -73,5 +76,12 @@ export function EventTimeRange({
/>
);
}
- return <TimeRange start={start} end={end} className={className} />;
+ return (
+ <TimeRange
+ start={start}
+ end={end}
+ showTimeZone={showTimeZone}
+ className={className}
+ />
+ );
}
diff --git a/apps/web/src/lib/datetime/constants.ts b/apps/web/src/lib/datetime/constants.ts
index dcee07a7a..a02f2e762 100644
--- a/apps/web/src/lib/datetime/constants.ts
+++ b/apps/web/src/lib/datetime/constants.ts
@@ -1,2 +1,3 @@
export const TIME_ZONE_COOKIE_NAME = "rallly_time_zone";
+export const TIME_ZONE_OVERRIDE_COOKIE_NAME = "rallly_time_zone_override";
export const TIME_FORMAT_COOKIE_NAME = "rallly_time_format";
diff --git a/apps/web/src/lib/datetime/device.ts b/apps/web/src/lib/datetime/device.ts
new file mode 100644
index 000000000..31d707a02
--- /dev/null
+++ b/apps/web/src/lib/datetime/device.ts
@@ -0,0 +1,37 @@
+"use client";
+
+import type { TimeFormat } from "@rallly/database";
+import Cookies from "js-cookie";
+import {
+ TIME_FORMAT_COOKIE_NAME,
+ TIME_ZONE_COOKIE_NAME,
+ TIME_ZONE_OVERRIDE_COOKIE_NAME,
+} from "@/lib/datetime/constants";
+
+const cookieAttributes = {
+ path: "/",
+ sameSite: "lax",
+ domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
+} as const;
+
+/**
+ * Session-scoped zone override for viewing times in another zone; wins over
+ * the detected zone (which TimeZoneSync keeps current). Picking the detected
+ * zone clears the override so it can't pin a stale zone after travel.
+ * No expiry: the override dies with the browser session.
+ */
+export function setTimeZoneOverride(timeZone: string) {
+ if (timeZone === Cookies.get(TIME_ZONE_COOKIE_NAME)) {
+ Cookies.remove(TIME_ZONE_OVERRIDE_COOKIE_NAME, cookieAttributes);
+ } else {
+ Cookies.set(TIME_ZONE_OVERRIDE_COOKIE_NAME, timeZone, cookieAttributes);
+ }
+}
+
+/** Per-device time format choice, read by getDeviceDateTimeConfig. */
+export function setDeviceTimeFormat(timeFormat: TimeFormat) {
+ Cookies.set(TIME_FORMAT_COOKIE_NAME, timeFormat, {
+ ...cookieAttributes,
+ expires: 365,
+ });
+}
diff --git a/apps/web/src/lib/datetime/format.ts b/apps/web/src/lib/datetime/format.ts
index a73194a2f..9ac1fb974 100644
--- a/apps/web/src/lib/datetime/format.ts
+++ b/apps/web/src/lib/datetime/format.ts
@@ -2,7 +2,7 @@ import type { TimeFormat } from "@rallly/database";
export type DateInput = Date | string | number;
-export type DatePreset = "date" | "dateLong" | "weekday";
+export type DatePreset = "date" | "dateLong" | "dateFull" | "weekday";
export type DateTimePreset = DatePreset | "time" | "datetime";
@@ -67,6 +67,13 @@ function presetOptions(
month: "long",
day: "numeric",
};
+ case "dateFull":
+ return {
+ weekday: "long",
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ };
case "weekday":
return { weekday: "long" };
case "datetime":
@@ -111,6 +118,47 @@ export function formatDate(
});
}
+export type DateParts = {
+ weekday: string;
+ day: string;
+ month: string;
+ year: string;
+};
+
+const partsFormatters = new Map<string, Intl.DateTimeFormat>();
+
+/**
+ * Decomposed short parts for chip-style UI (dow/day/month/year columns).
+ * One formatToParts call keeps the parts consistent with each other instead
+ * of running parallel formatters.
+ */
+export function formatDateParts(
+ value: DateInput,
+ options: { locale: string; timeZone?: string },
+): DateParts {
+ const key = `${options.locale}|${options.timeZone ?? ""}`;
+ let f = partsFormatters.get(key);
+ if (!f) {
+ f = new Intl.DateTimeFormat(options.locale, {
+ weekday: "short",
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+ // An empty string is an invalid IANA zone and throws; treat it as "unset".
+ timeZone: options.timeZone || undefined,
+ });
+ partsFormatters.set(key, f);
+ }
+
+ const parts: DateParts = { weekday: "", day: "", month: "", year: "" };
+ for (const part of f.formatToParts(toDate(value))) {
+ if (part.type in parts) {
+ parts[part.type as keyof DateParts] = part.value;
+ }
+ }
+ return parts;
+}
+
const relativeFormatters = new Map<string, Intl.RelativeTimeFormat>();
// Largest-first; each entry is how many of the unit make up the next one.
diff --git a/apps/web/src/lib/datetime/server.ts b/apps/web/src/lib/datetime/server.ts
index ddd06747d..d3ed17b5a 100644
--- a/apps/web/src/lib/datetime/server.ts
+++ b/apps/web/src/lib/datetime/server.ts
@@ -4,21 +4,26 @@ import { cookies } from "next/headers";
import {
TIME_FORMAT_COOKIE_NAME,
TIME_ZONE_COOKIE_NAME,
+ TIME_ZONE_OVERRIDE_COOKIE_NAME,
} from "@/lib/datetime/constants";
import { normalizeTimeFormat, normalizeTimeZone } from "@/lib/datetime/utils";
/**
* Device-scoped datetime config for public pages: the viewer's current zone
- * and their per-device format choice. Authenticated segments seed their
- * provider from the user's stored preferences instead. No zone means the
- * viewer's first ever request — components render times client-side once the
- * zone is known.
+ * and their per-device format choice. A session-scoped zone override (set
+ * from the clock preferences dialog) wins over the detected zone.
+ * Authenticated segments seed their provider from the user's stored
+ * preferences instead. No zone means the viewer's first ever request —
+ * components render times client-side once the zone is known.
*/
export async function getDeviceDateTimeConfig() {
const cookieStore = await cookies();
return {
- timeZone: normalizeTimeZone(cookieStore.get(TIME_ZONE_COOKIE_NAME)?.value),
+ timeZone:
+ normalizeTimeZone(
+ cookieStore.get(TIME_ZONE_OVERRIDE_COOKIE_NAME)?.value,
+ ) ?? normalizeTimeZone(cookieStore.get(TIME_ZONE_COOKIE_NAME)?.value),
timeFormat: normalizeTimeFormat(
cookieStore.get(TIME_FORMAT_COOKIE_NAME)?.value,
),