Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Utility to format dates relatively without having to specify units.
const { language = 'en-US' } = navigator;
const formatter = new Intl.RelativeTimeFormat(language, {
numeric: 'auto',
style: 'long',
});
export function formatRelative(when) {
const ms = when - Date.now();
const years = Math.ceil(ms / 31536e6);
if (years) return formatter.format(years, 'year');
const months = Math.ceil(ms / 168e6);
if (months) return formatter.format(months, 'month');
const days = Math.ceil(ms / 864e5);
if (days) return formatter.format(days, 'day');
const hours = Math.ceil(ms / 36e5);
if (hours) return formatter.format(hours, 'hour');
const minutes = Math.ceil(ms / 6e4);
if (minutes) return formatter.format(minutes, 'minute');
const seconds = Math.ceil(ms / 1e3);
return formatter.format(seconds, 'second');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment