Skip to content

Commit 8aebab9

Browse files
committed
fix: handle future at time ago
1 parent 038ca2d commit 8aebab9

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

packages/common-helpers/src/format.ts

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,19 +34,22 @@ export function formatAsCurrency(x: number): string {
3434
* @returns
3535
*/
3636
export function timeAgo(date: Date, locale = "en-US") {
37+
/** Difference in seconds */
3738
const difference = (new Date().getTime() - date.getTime()) / 1000;
38-
const minutes = Math.floor(difference / 60);
39-
const hours = Math.floor(minutes / 60);
40-
const days = Math.floor(hours / 24);
41-
const months = Math.floor(days / 30);
42-
const years = Math.floor(months / 12);
39+
const minutes = difference / 60;
40+
const hours = minutes / 60;
41+
const days = hours / 24;
42+
const months = days / 30;
43+
const years = months / 12;
4344
const relative = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
45+
// Use absolute value before rounding
46+
const moreThan = (v: number) => Math.floor(Math.abs(v)) > 0;
4447

45-
if (years > 0) return relative.format(0 - years, "year");
46-
else if (months > 0) return relative.format(0 - months, "month");
47-
else if (days > 0) return relative.format(0 - days, "day");
48-
else if (hours > 0) return relative.format(0 - hours, "hour");
49-
else if (minutes > 0) return relative.format(0 - minutes, "minute");
48+
if (moreThan(years)) return relative.format(0 - Math.floor(years), "year");
49+
else if (moreThan(months)) return relative.format(0 - Math.floor(months), "month");
50+
else if (moreThan(days)) return relative.format(0 - Math.floor(days), "day");
51+
else if (moreThan(hours)) return relative.format(0 - Math.floor(hours), "hour");
52+
else if (moreThan(minutes)) return relative.format(0 - Math.floor(minutes), "minute");
5053

5154
return relative.format(0 - difference, "second");
5255
}

0 commit comments

Comments
 (0)