/** * Shows a date as the time since it, beside every dump, comment, message and * notification. * * @module */ import { i18n } from "@lingui/core"; /** * Returns how long ago `date` was, as "3 minutes ago", in the current locale. * It is computed at render, so the text only moves on when the caller * re-renders. A month counts 30 days and a year 365. Every date shown is of * something that happened, so one in the future, which only a clock ahead of * this one can give, reads as "now". */ export function relativeTime(date: Date): string { const rtf = new Intl.RelativeTimeFormat(i18n.locale, { numeric: "auto" }); const abs = Math.max(0, Date.now() - date.getTime()) / 1000; if (abs < 60) return rtf.format(-Math.round(abs), "second"); if (abs < 3600) return rtf.format(-Math.round(abs / 60), "minute"); if (abs < 86400) return rtf.format(-Math.round(abs / 3600), "hour"); if (abs < 7 * 86400) return rtf.format(-Math.round(abs / 86400), "day"); if (abs < 30 * 86400) return rtf.format(-Math.round(abs / 7 / 86400), "week"); if (abs < 365 * 86400) { return rtf.format(-Math.round(abs / 30 / 86400), "month"); } return rtf.format(-Math.round(abs / 365 / 86400), "year"); }