diff options
Diffstat (limited to 'src/utils/datetime.ts')
-rw-r--r-- | src/utils/datetime.ts | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/src/utils/datetime.ts b/src/utils/datetime.ts index 3a2cd25..c32fde0 100644 --- a/src/utils/datetime.ts +++ b/src/utils/datetime.ts @@ -41,3 +41,28 @@ export function toIso8601FullUTC(date: Date): string { } const pad = (num: number, len = 2) => String(Math.abs(num)).padStart(len, "0"); + +export function getRelativeTimeUnit( + date: Date, + now: Date = new Date(), +): Parameters<Intl.RelativeTimeFormat["format"]> { + const diffMs = date.getTime() - now.getTime(); + + const seconds = diffMs / 1000; + const minutes = seconds / 60; + const hours = minutes / 60; + const days = hours / 24; + const weeks = days / 7; + const months = days / 30; + const quarters = months / 3; + const years = days / 365; + + if (Math.abs(years) >= 1) return [Math.round(years), "year"]; + if (Math.abs(quarters) >= 1) return [Math.round(quarters), "quarter"]; + if (Math.abs(months) >= 1) return [Math.round(months), "month"]; + if (Math.abs(weeks) >= 1) return [Math.round(weeks), "week"]; + if (Math.abs(days) >= 1) return [Math.round(days), "day"]; + if (Math.abs(hours) >= 1) return [Math.round(hours), "hour"]; + if (Math.abs(minutes) >= 1) return [Math.round(minutes), "minute"]; + return [Math.round(seconds), "second"]; +} |