-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #12426 from ethereum/markdown-date
feat: add LocaleDateTime for markdown time
- Loading branch information
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters