4 ms·
Look at `Intl.RelativeTimeFormat`[1] and `Intl.DateTimeFormat`[2]. Regrettably Safari is—yet again—lacking with support, but in the meantime there is a polyfil
by runarberg 6y ago
Look at `Intl.RelativeTimeFormat`[1] and `Intl.DateTimeFormat`[2].
Regrettably Safari is—yet again—lacking with support, but in the meantime there is a polyfill.
1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- chrismorgan 6y agoI find RelativeTimeFormat to be not as useful as it seems—it’s surprisingly limited in scope and utility. You still have to calculate the magnitude and unit of the distance (“3 hours ago” → (3, 'hour') rather than saying “here’s a Date object that happens to be about three hours in the future, you tell me what unit to show”), and it only supports one unit at a time (“1 day ago” or “27 hours ago”, not anything like “1 day, 3 hours ago”), and it can’t produce anything like “next Tuesday” or “this Friday”. Twice I’ve started with it, twice I’ve tossed it out because in the end it didn’t help my code at all. (Both times I only cared about English, so its replacement which did a better job of formatting values for my situation took pretty much no extra code—for exact equivalence, formatter.format(-n, 'day') for known positive n becomes a simple ternary, `n == 1 ? '1 day ago' : '${n} days ago'` (or if the formatter has the {numeric: 'auto'} option, change '1 day ago' to 'yesterday'); but even with full localisation, I’d still be unlikely to use RelativeTimeFormat.)
- runarberg 6y agoI guess Temporal will help you there[1]: const now = Temporal.now.absolute(); const then = Temporal.Absolute.from( '1989-11-09T22:45:00+0100[Europe/Berlin]', ); const sinceThen = now.difference(then); sinceThen.toLocaleString('en'); 1: https://tc39.es/proposal-temporal/docs/duration.html#toLocaleString https://tc39.es/proposal-temporal/docs/duration.html#toLocal...