Skip to content

Instantly share code, notes, and snippets.

@SmartArray
Created January 14, 2025 15:04
Show Gist options
  • Save SmartArray/3128adca81cd20aba95b0f2b10bf3d55 to your computer and use it in GitHub Desktop.
Save SmartArray/3128adca81cd20aba95b0f2b10bf3d55 to your computer and use it in GitHub Desktop.
Displays the time difference in words for a past or future Date object, e.g. 20 seconds left or 5 days ago
export function renderSeconds(seconds: number, suffix: string): string {
if (seconds < 0) return `0 seconds ${suffix}`;
if (seconds < 60) {
return `${seconds} second${seconds === 1 ? '' : 's'} ${suffix}`;
}
const minutes = Math.floor(seconds / 60);
if (minutes < 60) {
return `${minutes} minute${minutes === 1 ? '' : 's'} ${suffix}`;
}
const hours = Math.floor(minutes / 60);
if (hours < 24) {
return `${hours} hour${hours === 1 ? '' : 's'} ${suffix}`;
}
const days = Math.floor(hours / 24);
if (days < 30) {
return `${days} day${days === 1 ? '' : 's'} ${suffix}`;
}
const months = Math.floor(days / 30);
if (months < 12) {
return `${months} month${months === 1 ? '' : 's'} ${suffix}`;
}
const years = Math.floor(months / 12);
return `${years} year${years === 1 ? '' : 's'} ${suffix}`;
};
export function timeAgo(date: Date, suffix: string = 'ago'): string {
const seconds = Math.floor((new Date().getTime() - date.getTime()) / 1000);
return renderSeconds(seconds, suffix);
};
export function timeTo(date: Date, suffix: string = 'left'): string {
const seconds = Math.floor((date.getTime() - new Date().getTime()) / 1000);
return renderSeconds(seconds, suffix);
};
export function timeDiff(date: Date | null): string {
if (date == null || date.getTime() === 0) {
return '-';
}
if (new Date() > date) {
return timeAgo(date);
} else {
return timeTo(date);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment