nej-react-utils/format.js
honzapatCZ 8863c7bf90 format
2024-10-19 10:57:45 +02:00

56 lines
1.4 KiB
JavaScript

import { useTranslation } from "react-i18next";
export function useNumberFormat() {
const { i18n } = useTranslation();
return (number, digits=2, currency=null) => {
if (currency) {
if((Math.round(number * (10**digits))/(10**digits)) === 0)
return "---";
return new Intl.NumberFormat(i18n.language, {
style: "currency",
currency: currency,
minimumFractionDigits: digits,
maximumFractionDigits: digits,
}).format(number);
} else {
return new Intl.NumberFormat(i18n.language, {
minimumFractionDigits: digits,
maximumFractionDigits: digits,
}).format(number);
}
}
}
export function useDateFormat() {
const { i18n } = useTranslation();
return (date) => {
if(typeof date === "undefined") return "---";
if(typeof date === "string") date = new Date(date);
return new Intl.DateTimeFormat(i18n.language, {
year: "numeric",
month: "short",
day: "numeric",
}).format(date);
}
}
export function useDateTimeFormat() {
const { i18n } = useTranslation();
return (date) => {
if(typeof date === "undefined") return "---";
if(typeof date === "string") date = new Date(date);
return new Intl.DateTimeFormat(i18n.language, {
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).format(date);
}
}