Created
April 23, 2021 10:08
-
-
Save hypeJunction/1949550fdfb0d6f69c505cbb50f215cb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import moment from "moment"; | |
| export enum DateTimeFormat { | |
| HUMAN, | |
| ISO, | |
| } | |
| export interface DateTimeFormatterProps { | |
| format: DateTimeFormat; | |
| date: Date; | |
| } | |
| type DateTimeFormatFn = (props: DateTimeFormatterProps) => string; | |
| export interface DateTimeFormatter { | |
| formatDateTime: DateTimeFormatFn; | |
| } | |
| const momentFormats = { | |
| [DateTimeFormat.HUMAN]: (date: Date): string => { | |
| return moment(date).format("ddd, hA"); | |
| }, | |
| [DateTimeFormat.ISO]: (date: Date): string => { | |
| return date.toISOString(); | |
| }, | |
| }; | |
| const momentFormatter: DateTimeFormatFn = ( | |
| props: DateTimeFormatterProps | |
| ): string => { | |
| const { format, date } = props; | |
| return momentFormats[format](date); | |
| }; | |
| export function useDateTimeFormatter(): DateTimeFormatter { | |
| return { | |
| formatDateTime: momentFormatter, | |
| }; | |
| } |
This file contains hidden or 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
| import { | |
| DateTimeFormat, | |
| DateTimeFormatterProps, | |
| useDateTimeFormatter, | |
| } from "./utils/datetime"; | |
| export const FormattedDateTime = ({ format, date }: DateTimeFormatterProps) => { | |
| const { formatDateTime } = useDateTimeFormatter(); | |
| return ( | |
| <time | |
| dateTime={formatDateTime({ | |
| format: DateTimeFormat.ISO, | |
| date, | |
| })} | |
| > | |
| {formatDateTime({ format, date })} | |
| </time> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment