Files
memind/src/utils/time.ts
T

37 lines
1.0 KiB
TypeScript
Raw Normal View History

const pad = (n: number) => String(n).padStart(2, '0');
function sameDay(a: Date, b: Date) {
return (
a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate() === b.getDate()
);
}
export function formatChatTime(timestampSec: number): string {
const date = new Date(timestampSec * 1000);
const now = new Date();
const time = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
if (sameDay(date, now)) {
return time;
}
const yesterday = new Date(now);
yesterday.setDate(yesterday.getDate() - 1);
if (sameDay(date, yesterday)) {
return `昨天 ${time}`;
}
if (date.getFullYear() === now.getFullYear()) {
return `${date.getMonth() + 1}月${date.getDate()}日 ${time}`;
}
return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${time}`;
}
export function shouldShowTimestamp(currentSec: number, previousSec?: number): boolean {
if (previousSec === undefined) return true;
return currentSec - previousSec > 5 * 60;
}