@scaleway/use-i18n
Version:
A small hook to handle i18n
55 lines (54 loc) • 1.81 kB
JavaScript
import { formatISO, intlFormat } from "date-fns";
//#region src/formatDate.ts
const formatOptions = {
hour: {
day: "numeric",
hour: "numeric",
minute: "numeric",
month: "long",
year: "numeric"
},
hourOnly: {
hour: "numeric",
minute: "numeric"
},
long: {
day: "numeric",
month: "long",
year: "numeric"
},
second: {
day: "numeric",
hour: "numeric",
minute: "numeric",
month: "long",
second: "numeric",
year: "numeric"
},
short: {
day: "numeric",
month: "short",
year: "numeric"
},
shortWithoutDay: {
month: "short",
year: "numeric"
}
};
const complexFormatOptions = {
numeric: (date) => formatISO(date, { representation: "date" }),
numericHour: (date, locale) => `${formatISO(date, { representation: "date" })} ${intlFormat(date, formatOptions.hourOnly, { locale })}`
};
const keyFormatOptions = Object.keys(formatOptions);
const keyComplexFormatOptions = Object.keys(complexFormatOptions);
const supportedFormats = [.../* @__PURE__ */ new Set([...keyFormatOptions, ...keyComplexFormatOptions])];
const formatDate = (locale, date, format = "short") => {
if (typeof format === "string" && !(format in formatOptions || format in complexFormatOptions)) throw new Error(`format "${format}" should be one of ${supportedFormats.join(", ")} or a valid Intl.DateTimeFormat options object`);
const properDate = typeof date === "string" || typeof date === "number" ? new Date(date) : date;
if (typeof format === "string" && format in complexFormatOptions) return complexFormatOptions[format](properDate, locale);
const options = typeof format === "string" ? formatOptions[format] : format;
if (properDate instanceof Date) return intlFormat(properDate, options, { locale });
return properDate;
};
//#endregion
export { formatDate as default, supportedFormats };