51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
import type { Locale } from "./i18n";
|
|
|
|
function intlLocale(locale: Locale): string {
|
|
if (locale === "zh-Hant") return "zh-TW";
|
|
if (locale === "zh-Hans") return "zh-CN";
|
|
if (locale === "ja") return "ja-JP";
|
|
return "en";
|
|
}
|
|
|
|
export function formatClock(iso: string, locale: Locale): string {
|
|
const date = new Date(iso);
|
|
if (Number.isNaN(date.getTime())) return "";
|
|
return new Intl.DateTimeFormat(intlLocale(locale), {
|
|
hour: "numeric",
|
|
minute: "2-digit",
|
|
}).format(date);
|
|
}
|
|
|
|
export function formatDay(iso: string, locale: Locale): string {
|
|
const date = new Date(iso);
|
|
if (Number.isNaN(date.getTime())) return "";
|
|
const now = new Date();
|
|
const start = (d: Date) => Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
|
|
const diff = Math.round((start(now) - start(date)) / 86400000);
|
|
if (diff === 0) {
|
|
if (locale === "en") return "Today";
|
|
if (locale === "ja") return "今日";
|
|
if (locale === "zh-Hans") return "今天";
|
|
return "今天";
|
|
}
|
|
if (diff === 1) {
|
|
if (locale === "en") return "Yesterday";
|
|
if (locale === "ja") return "昨日";
|
|
if (locale === "zh-Hans") return "昨天";
|
|
return "昨天";
|
|
}
|
|
return new Intl.DateTimeFormat(intlLocale(locale), { dateStyle: "medium" }).format(date);
|
|
}
|
|
|
|
export function sameLocalDay(a?: string, b?: string): boolean {
|
|
if (!a || !b) return false;
|
|
const left = new Date(a);
|
|
const right = new Date(b);
|
|
if (Number.isNaN(left.getTime()) || Number.isNaN(right.getTime())) return false;
|
|
return (
|
|
left.getFullYear() === right.getFullYear() &&
|
|
left.getMonth() === right.getMonth() &&
|
|
left.getDate() === right.getDate()
|
|
);
|
|
}
|