mirror of
https://github.com/block/buzz.git
synced 2026-10-31 14:31:02 +00:00
19 lines
734 B
TypeScript
19 lines
734 B
TypeScript
/** Format a Unix timestamp (seconds) as a human-readable relative time string. */
|
|
export function relativeTime(unix: number): string {
|
|
const diff = Date.now() - unix * 1000;
|
|
const seconds = Math.floor(diff / 1000);
|
|
const minutes = Math.floor(seconds / 60);
|
|
const hours = Math.floor(minutes / 60);
|
|
const days = Math.floor(hours / 24);
|
|
|
|
if (days > 30) {
|
|
const months = Math.floor(days / 30);
|
|
return months === 1 ? "1 month ago" : `${months} months ago`;
|
|
}
|
|
if (days > 0) return days === 1 ? "1 day ago" : `${days} days ago`;
|
|
if (hours > 0) return hours === 1 ? "1 hour ago" : `${hours} hours ago`;
|
|
if (minutes > 0)
|
|
return minutes === 1 ? "1 minute ago" : `${minutes} minutes ago`;
|
|
return "just now";
|
|
}
|