File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change @@ -40,6 +40,7 @@ import Emoji from "./Emoji"
40
40
import ExpandableCard from "./ExpandableCard"
41
41
import FeaturedText from "./FeaturedText"
42
42
import InfoBanner from "./InfoBanner"
43
+ import LocaleDateTime from "./LocaleDateTime"
43
44
import MainArticle from "./MainArticle"
44
45
45
46
/**
@@ -160,6 +161,7 @@ export const htmlElements = {
160
161
ol : OrderedList ,
161
162
p : Paragraph ,
162
163
pre : Pre ,
164
+ time : LocaleDateTime ,
163
165
ul : UnorderedList ,
164
166
...mdxTableComponents ,
165
167
}
You can’t perform that action at this time.
0 commit comments