54 lines
1.5 KiB
TypeScript
54 lines
1.5 KiB
TypeScript
import { createLocaleFormatters, type LocaleFormatters, useLocaleFormatters } from "~/locale/format";
|
|
|
|
export type DateFormatType = "YYYY-MM-DD" | "DD-MM-YYYY" | "MM-DD-YYYY" | "diff";
|
|
|
|
const fallbackFormatters = createLocaleFormatters("en");
|
|
|
|
function padDatePart(value: number) {
|
|
return value.toString().padStart(2, "0");
|
|
}
|
|
|
|
function formatExplicitDate(value: Date, pattern: Exclude<DateFormatType, "diff">) {
|
|
const year = value.getFullYear();
|
|
const month = padDatePart(value.getMonth() + 1);
|
|
const day = padDatePart(value.getDate());
|
|
if (pattern === "YYYY-MM-DD") {
|
|
return `${year}-${month}-${day}`;
|
|
}
|
|
if (pattern === "DD-MM-YYYY") {
|
|
return `${day}-${month}-${year}`;
|
|
}
|
|
return `${month}-${day}-${year}`;
|
|
}
|
|
|
|
export function getDateAsString({
|
|
value,
|
|
format,
|
|
formatters = fallbackFormatters,
|
|
}: {
|
|
value?: Date | null;
|
|
format?: DateFormatType;
|
|
formatters?: LocaleFormatters;
|
|
}) {
|
|
if (!value) {
|
|
return "";
|
|
}
|
|
|
|
switch (format) {
|
|
case "YYYY-MM-DD":
|
|
case "DD-MM-YYYY":
|
|
case "MM-DD-YYYY":
|
|
return formatExplicitDate(value, format);
|
|
case "diff":
|
|
return formatters.relativeDate(value);
|
|
default:
|
|
return formatters.date(value, { dateStyle: "medium" });
|
|
}
|
|
}
|
|
|
|
export default function RowDateCell({ value, format }: { value?: Date | null; format?: DateFormatType }) {
|
|
const formatters = useLocaleFormatters();
|
|
const text = getDateAsString({ value, format, formatters });
|
|
return <>{!value ? <div></div> : <div>{text}</div>}</>;
|
|
}
|