-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathtimeAgo.ts
24 lines (22 loc) · 948 Bytes
/
timeAgo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Copyright 2024 the JSR authors. All rights reserved. MIT license.
export function timeAgo(date: Date | string): string {
const now = new Date();
const past = new Date(date);
const diff = Math.abs(now.getTime() - past.getTime());
const duration = {
years: Math.floor(diff / (1000 * 60 * 60 * 24 * 365)),
months: Math.floor(
(diff % (1000 * 60 * 60 * 24 * 365)) / (1000 * 60 * 60 * 24 * 30),
),
days: Math.floor(
(diff % (1000 * 60 * 60 * 24 * 30)) / (1000 * 60 * 60 * 24),
),
hours: Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes: Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)),
seconds: Math.floor((diff % (1000 * 60)) / 1000),
};
// Force english because JSR is an English-only project
// @ts-ignore - TS doesn't know about this API yet
const formatter = new Intl.DurationFormat("en", { style: "long" });
return formatter.format(duration) + " ago";
}