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 default (when) => {
const ms = when - Date.now();
const years = Math.ceil(ms / 31536e6);
if (years) return formatter.format(years, 'years');
const days = Math.ceil(ms / 864e5);
if (days) return formatter.format(days, 'days');
const hours = Math.ceil(ms / 36e5);
if (hours) return formatter.format(hours, 'hours');
const minutes = Math.ceil(ms / 6e4);
if (minutes) return formatter.format(minutes, 'minutes');
return 'Just now';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.