S
SolidJS2y ago
ry

Handling locale dates when SSR

I am trying to display a date with date.toLocaleDateString, however as the page is SSR it is instead showing as the server's locale. Is there a pattern to handle this?
10 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
ry
ryOP2y ago
You mean by passing the locale in the url right? I'm thinking if there's an easy to only render/rerender the dates on client
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
ry
ryOP2y ago
Thanks will take a look at that article The concern for me is displaying the date in the user's timezone
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
ry
ryOP2y ago
Yeah I'm leaning towards 2) was wondering if anyone else has a good pattern for implementing this
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
ry
ryOP2y ago
Came across this as well, would be so much better if there was a html element to do this
Razboy20
Razboy202y ago
For my own project, I deal with this issue by setting the user's timezone to the cookies: I have two functions:
// Serverside
export const getCookieTimezone = (): string => {
if (!isServer) throw new Error("Server-side only");

const event = useServerContext();
const cookie = parseCookie(event.request.headers.get("cookie") ?? "");

return cookie.timezone;
};

// Clientside in root.tsx
if (!isServer) {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
document.cookie = `timezone=${tz};path=/;max-age=31536000`;
}
// Serverside
export const getCookieTimezone = (): string => {
if (!isServer) throw new Error("Server-side only");

const event = useServerContext();
const cookie = parseCookie(event.request.headers.get("cookie") ?? "");

return cookie.timezone;
};

// Clientside in root.tsx
if (!isServer) {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
document.cookie = `timezone=${tz};path=/;max-age=31536000`;
}
On the very first load, it wouldn't know the time zone, however at least for my own project, there is a login page/a root page that a user loads before any times are even shown.
ry
ryOP2y ago
Thanks for sharing. I have pages that have dates on first load, so I opted to render as UTC and update on client.
const LocaleDate: Component<Props> = (props) => {
const [display, setDisplay] = createSignal<string>(
formatDate(props.date, {
timeZone: "Etc/UTC",
}) + " (UTC)"
);

createEffect(() => {
setDisplay(formatDate(props.date));
});

return <time datetime={props.date.toISOString()}>{display()}</time>;
};
const LocaleDate: Component<Props> = (props) => {
const [display, setDisplay] = createSignal<string>(
formatDate(props.date, {
timeZone: "Etc/UTC",
}) + " (UTC)"
);

createEffect(() => {
setDisplay(formatDate(props.date));
});

return <time datetime={props.date.toISOString()}>{display()}</time>;
};
Want results from more Discord servers?
Add your server