-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalTime.tsx
More file actions
43 lines (38 loc) · 1.31 KB
/
Copy pathLocalTime.tsx
File metadata and controls
43 lines (38 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
'use client';
import { useEffect, useState } from 'react';
/**
* Deterministic fallback used for SSR and the first client render — a fixed
* locale + timezone so the server- and client-rendered HTML are identical
* (no hydration mismatch).
*/
const STABLE_FORMAT = new Intl.DateTimeFormat('en-GB', {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'UTC',
});
/**
* Renders a timestamp in the VISITOR's own locale and timezone — the
* senior-correct i18n choice — without a hydration mismatch.
*
* The trick: render a fixed UTC value on the server and the first client paint
* (so the markup matches), then, after mount, re-format with the browser's
* actual locale/timezone (`Intl.DateTimeFormat(undefined, …)` reads the user's
* settings). The swap is a normal post-mount state update, not a mismatch.
* Output is a semantic `<time>` element carrying the machine-readable ISO value.
*/
export function LocalTime({ iso }: { iso: string }) {
const [text, setText] = useState(() => `${STABLE_FORMAT.format(new Date(iso))} UTC`);
useEffect(() => {
setText(
new Intl.DateTimeFormat(undefined, {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date(iso)),
);
}, [iso]);
return (
<time dateTime={iso} suppressHydrationWarning>
{text}
</time>
);
}