nej-react-utils/misc/format.ts

86 lines
2.2 KiB
TypeScript

import { useCallback } from "react";
import { useTranslation } from "react-i18next";
export function useNumberFormat() {
const { i18n } = useTranslation();
return (number: number, digits = 2, currency = null) => {
if(number == undefined)
return 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: Date | string) => {
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: Date | string) => {
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);
}
}
export function useLanguageFormat(){
const { i18n } = useTranslation();
return useCallback((language: string) => {
if(language.toLowerCase() == "zh_cn")
language = "zh-Hans";
else if (language.toLowerCase() == "zh_tw")
language = "zh-Hant";
return new Intl.DisplayNames(i18n.language, {
type: "language",
style: "short",
}).of(language);
}, [i18n.language]);
}
export function useCountryFormat(){
const { i18n } = useTranslation();
return (region: string) => {
return new Intl.DisplayNames(i18n.language, {
type: "region",
style: "short",
}).of(region);
}
}