Skip to content

Commit

Permalink
Merge pull request #12426 from ethereum/markdown-date
Browse files Browse the repository at this point in the history
feat: add LocaleDateTime for markdown time
  • Loading branch information
nhsz authored Mar 12, 2024
2 parents a1feedc + ec3f0d9 commit 31dccb7
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/components/LocaleDateTime.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { useRouter } from "next/router"

type LocaleDateTimeProps = {
utcDateTime: string
hideDate?: boolean
hideTime?: boolean
options?: Intl.DateTimeFormatOptions
}

/**
* Renders a localized date and time component
* @param utcDateTime - The UTC date and time string, ie "2022-04-20T16:20:00Z"
* @param hideDate - Whether to hide the date portion
* @param hideTime - Whether to hide the time portion
* @param options - Options override for formatting the date and time
* @returns The rendered LocaleDateTime component
*/
const LocaleDateTime = ({
utcDateTime,
hideDate,
hideTime,
options,
}: LocaleDateTimeProps) => {
if (hideDate && hideTime)
throw new Error(
"LocaleDateTime hideDate and hideTime props cannot both be true"
)

const { locale } = useRouter()
const date = new Date(utcDateTime)
const defaultDateOptions: Intl.DateTimeFormatOptions = {
month: "long",
day: "numeric",
year: "numeric",
}
const defaultTimeOptions: Intl.DateTimeFormatOptions = {
hour: "numeric",
minute: "numeric",
second: "numeric",
}
const dateTimeOptions: Intl.DateTimeFormatOptions = {
...(hideDate ? {} : defaultDateOptions),
...(hideTime ? {} : defaultTimeOptions),
...options,
}
return (
<time dateTime={utcDateTime}>
{new Intl.DateTimeFormat(locale, dateTimeOptions).format(date)}
</time>
)
}

export default LocaleDateTime
2 changes: 2 additions & 0 deletions src/components/MdComponents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import Emoji from "./Emoji"
import ExpandableCard from "./ExpandableCard"
import FeaturedText from "./FeaturedText"
import InfoBanner from "./InfoBanner"
import LocaleDateTime from "./LocaleDateTime"
import MainArticle from "./MainArticle"
import VideoIframe from "./VideoIframe"

Expand Down Expand Up @@ -161,6 +162,7 @@ export const htmlElements = {
ol: OrderedList,
p: Paragraph,
pre: Pre,
time: LocaleDateTime,
ul: UnorderedList,
iframe: VideoIframe,
...mdxTableComponents,
Expand Down

0 comments on commit 31dccb7

Please sign in to comment.