Skip to content

Instantly share code, notes, and snippets.

@arabold
Created March 4, 2020 21:21
Show Gist options
  • Save arabold/3c81c44ce98348ed218c972072190845 to your computer and use it in GitHub Desktop.
Save arabold/3c81c44ce98348ed218c972072190845 to your computer and use it in GitHub Desktop.
import Intl from "intl";
import React, { useMemo } from "react";
import useLocalization from "./useLocalization";
export interface DateTimeFormatProps {
/** The value to format */
value: Date | string | number;
/** Override system locale (not recommended) */
locale?: string;
/** Options */
weekday: "narrow" | "short" | "long";
era: "narrow" | "short" | "long";
year: "numeric" | "2-digit";
month: "numeric" | "2-digit" | "narrow" | "short" | "long";
day: "numeric" | "2-digit";
hour: "numeric" | "2-digit";
minute: "numeric" | "2-digit";
second: "numeric" | "2-digit";
timeZoneName: "short" | "long";
/** Time zone to express it in, e.g. "Asia/Shanghai" */
timeZone: string;
/** Force 12-hour or 24-hour */
hour12: boolean;
/** Rarely-used options */
hourCycle: "h11" | "h12" | "h23" | "h24";
formatMatcher: "basic" | "best fit";
}
/**
* @see [DateTimeFormat Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat)
* @see [Intl.DateTimeFormat cheatsheet](https://devhints.io/wip/intl-datetime)
*/
export default function DateTimeFormat({ value, locale: customLocale, ...props }: DateTimeFormatProps) {
const { locale: defaultLocale } = useLocalization();
const locale = customLocale ?? defaultLocale;
const intl = useMemo(() => new Intl.DateTimeFormat(locale, { ...props }), [props, locale]);
return <>{intl.format(typeof value === "string" ? new Date(value) : value)}</>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment