Skip to content

Instantly share code, notes, and snippets.

@guzmanoj
Forked from liamnewmarch/format-relative.js
Created May 19, 2020 16:21
Show Gist options
  • Save guzmanoj/85072ea8d944a20dec71fade84a56da6 to your computer and use it in GitHub Desktop.
Save guzmanoj/85072ea8d944a20dec71fade84a56da6 to your computer and use it in GitHub Desktop.
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