Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save flipeador/d23573b2e38cca27c9684ac8382cd9bf to your computer and use it in GitHub Desktop.

Select an option

Save flipeador/d23573b2e38cca27c9684ac8382cd9bf to your computer and use it in GitHub Desktop.
Language-sensitive relative time formatting in JavaScript.
/**
* Language-sensitive relative time formatting.
* @see https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat
* @example
* // now
* console.log(formatRelativeTime(
* '2000/01/01 00:00:00',
* '2000/01/01 00:00:00'
* ));
*
* // next month
* console.log(formatRelativeTime(
* '2000/02/01 00:00:00',
* '2000/01/01 00:00:00'
* ));
*
* // 2 years ago
* console.log(formatRelativeTime(
* '2000/01/01 00:00:00',
* '2001/01/01 00:00:00'
* ));
*/
function formatRelativeTime(ts1, ts2, fmt)
{
ts1 = (new Date(ts1)).getTime();
ts2 = ts2 ? (new Date(ts2)).getTime() : Date.now();
const elapsed = Math.round((ts1 - ts2) / 1000);
const difference = Math.abs(elapsed);
fmt = { numeric: 'auto', ...fmt };
fmt.units ??= {
year: 31536000,
month: 2629800,
week: 604800,
day: 86400,
hour: 3600,
minute: 60
};
const rtf = new Intl.RelativeTimeFormat(fmt?.locale || undefined, fmt);
for (const unit in fmt.units) {
if (difference >= fmt.units[unit]) {
return rtf.format(
Math.floor(elapsed / fmt.units[unit]),
unit
);
}
}
return rtf.format(elapsed, 'second');
}
@flipeador
Copy link
Copy Markdown
Author

flipeador commented Aug 6, 2024

Temporal.ZonedDateTime.from('2025-04-14T10:00[America/New_York]')
  .withTimeZone(Temporal.Now.timeZoneId()) // your time zone
  .toLocaleString(navigator.language);
  
navigator.language; // seems a better choice than ↓
new Intl.DateTimeFormat().resolvedOptions().locale;

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