@intility/bifrost-react
Version:
React library for Intility's design system, Bifrost.
39 lines (38 loc) • 1.53 kB
JavaScript
import { useCallback } from "react";
import useLocale from "./useLocale.js";
// cache each formatter as it is created
const formattersCache = {};
function getDateFormatter(locale, options) {
// is this actually less expensive than creating a new formatter?
const key = JSON.stringify({
locale,
options
});
let formatter = formattersCache[key];
if (!formatter || typeof formatter.format !== "function") {
formatter = new Intl.DateTimeFormat(locale, options);
formattersCache[key] = formatter;
}
return formatter;
}
/**
* Context-aware date and time formatter using locale and options from the current Bifrost context unless specified
* @returns A function that formats a date and/or time
*/ export default function useDateTimeFormatter() {
const { dateOptions } = useLocale();
return useCallback(/**
* Formats the date and/or time
* @returns A formatted date string
*/ function dateTimeFormatter({ date, show, locale, options }) {
date = typeof date === "string" ? new Date(date) : date;
show = show ?? "date";
locale = locale ?? dateOptions.locale;
options = options ?? (show === "date" ? dateOptions.date : show === "time" ? dateOptions.time : {
...dateOptions.time,
...dateOptions.date
});
return show === "date" ? getDateFormatter(locale, options).format(date) : getDateFormatter(locale, options).format(date).replace(",", "");
}, [
dateOptions
]);
}