Fix relative time ago exceeding 24 hours

This commit is contained in:
Lim Chee Aun 2024-08-15 09:09:57 +08:00
parent ac94303d0c
commit 377ad11c1a

View file

@ -66,31 +66,31 @@ export default function RelativeTime({ datetime, format }) {
const date = useMemo(() => dayjs(datetime), [datetime]); const date = useMemo(() => dayjs(datetime), [datetime]);
const [dateStr, dt, title] = useMemo(() => { const [dateStr, dt, title] = useMemo(() => {
if (!date.isValid()) return ['' + datetime, '', '']; if (!date.isValid()) return ['' + datetime, '', ''];
const realDate = date.toDate();
let str; let str;
if (format === 'micro') { if (format === 'micro') {
// If date <= 1 day ago or day is within this year // If date <= 1 day ago or day is within this year
const now = dayjs(); const now = new Date();
const dayDiff = now.diff(date, 'day'); const dayDiff = (now.getTime() - realDate.getTime()) / 1000 / day;
if (dayDiff <= 1) { if (dayDiff <= 1) {
str = twitterFromNow(date.toDate()); str = twitterFromNow(realDate);
} else { } else {
const currentYear = now.year(); const sameYear = now.getFullYear() === realDate.getFullYear();
const dateYear = date.year(); if (sameYear) {
if (dateYear === currentYear) {
str = DTF(i18n.locale, { str = DTF(i18n.locale, {
year: undefined, year: undefined,
month: 'short', month: 'short',
day: 'numeric', day: 'numeric',
}).format(date.toDate()); }).format(realDate);
} else { } else {
str = DTF(i18n.locale, { str = DTF(i18n.locale, {
dateStyle: 'short', dateStyle: 'short',
}).format(date.toDate()); }).format(realDate);
} }
} }
} }
if (!str) str = rtfFromNow(date.toDate()); if (!str) str = rtfFromNow(realDate);
return [str, date.toISOString(), date.toDate().toLocaleString()]; return [str, realDate.toISOString(), realDate.toLocaleString()];
}, [date, format, renderCount]); }, [date, format, renderCount]);
useEffect(() => { useEffect(() => {