-
-
Save wall-street-dev/85072ea8d944a20dec71fade84a56da6 to your computer and use it in GitHub Desktop.
Utility to format dates relatively without having to specify units.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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