Skip to content

Commit ec3f0d9

Browse files
committed
feat: add LocaleDateTime for markdown time
1 parent 2ce32ca commit ec3f0d9

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/components/LocaleDateTime.tsx

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { useRouter } from "next/router"
2+
3+
type LocaleDateTimeProps = {
4+
utcDateTime: string
5+
hideDate?: boolean
6+
hideTime?: boolean
7+
options?: Intl.DateTimeFormatOptions
8+
}
9+
10+
/**
11+
* Renders a localized date and time component
12+
* @param utcDateTime - The UTC date and time string, ie "2022-04-20T16:20:00Z"
13+
* @param hideDate - Whether to hide the date portion
14+
* @param hideTime - Whether to hide the time portion
15+
* @param options - Options override for formatting the date and time
16+
* @returns The rendered LocaleDateTime component
17+
*/
18+
const LocaleDateTime = ({
19+
utcDateTime,
20+
hideDate,
21+
hideTime,
22+
options,
23+
}: LocaleDateTimeProps) => {
24+
if (hideDate && hideTime)
25+
throw new Error(
26+
"LocaleDateTime hideDate and hideTime props cannot both be true"
27+
)
28+
29+
const { locale } = useRouter()
30+
const date = new Date(utcDateTime)
31+
const defaultDateOptions: Intl.DateTimeFormatOptions = {
32+
month: "long",
33+
day: "numeric",
34+
year: "numeric",
35+
}
36+
const defaultTimeOptions: Intl.DateTimeFormatOptions = {
37+
hour: "numeric",
38+
minute: "numeric",
39+
second: "numeric",
40+
}
41+
const dateTimeOptions: Intl.DateTimeFormatOptions = {
42+
...(hideDate ? {} : defaultDateOptions),
43+
...(hideTime ? {} : defaultTimeOptions),
44+
...options,
45+
}
46+
return (
47+
<time dateTime={utcDateTime}>
48+
{new Intl.DateTimeFormat(locale, dateTimeOptions).format(date)}
49+
</time>
50+
)
51+
}
52+
53+
export default LocaleDateTime

src/components/MdComponents.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import Emoji from "./Emoji"
4040
import ExpandableCard from "./ExpandableCard"
4141
import FeaturedText from "./FeaturedText"
4242
import InfoBanner from "./InfoBanner"
43+
import LocaleDateTime from "./LocaleDateTime"
4344
import MainArticle from "./MainArticle"
4445

4546
/**
@@ -160,6 +161,7 @@ export const htmlElements = {
160161
ol: OrderedList,
161162
p: Paragraph,
162163
pre: Pre,
164+
time: LocaleDateTime,
163165
ul: UnorderedList,
164166
...mdxTableComponents,
165167
}

0 commit comments

Comments
 (0)