Skip to content

Instantly share code, notes, and snippets.

@liamnewmarch
Last active November 3, 2023 15:29
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save liamnewmarch/a345fbf0c4fdf938d9844b82a4f127ab to your computer and use it in GitHub Desktop.
Save liamnewmarch/a345fbf0c4fdf938d9844b82a4f127ab to your computer and use it in GitHub Desktop.
Relative time strings using the web platform
/**
* The target language. [Browser support is good][1] but "en-US" is a safe default.
*
* [1]: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language
*
* @type {string}
*/
const { language = "en-US" } = navigator;
/**
* Instance of the relative time format object for the target language. [Browser
* support for this][2] is less good, though [polyfills][3] are available.
*
* [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat
* [3]: https://github.com/tc39/proposal-intl-relative-time#polyfills
* @type {Intl.RelativeTimeFormat}
*/
const formatter = new Intl.RelativeTimeFormat(language, {
numeric: "auto",
style: "long",
});
/**
* Mapping from a Intl.RelativeTimeFormat unit string to the equivalent value
* in milliseconds.
*
* @type {{[unit: string]: number}}
*/
const units = {
year: 31_557_600_000, // Approx. 86,400 seconds per day * 365.25 days.
month: 2_629_800_000, // Approx. 31,557,600 seconds per year / 12 months.
day: 86_400_000,
hour: 3_600_000,
minute: 60_000,
second: 1_000,
};
/**
* Return an Intl.RelativeTimeFormat string without having to specify units.
*
* @param {Date} when
* @returns {string}
*/
export function formatRelative(when) {
const ms = when - Date.now();
for (const [unit, value] of Object.entries(units)) {
const amount = Math.ceil(ms / value);
if (amount || unit === 'second') {
return formatter.format(amount, unit);
}
}
}
@vhoyer
Copy link

vhoyer commented May 19, 2020

yeah, I wanted a "just now" equivalent haha, but I guess the seconds are fine 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment