intl

Intl.RelativeTimeFormat

Formats relative times such as '3 days ago' or 'in 2 hours' in a locale-aware way, replacing hand-rolled 'time ago' helpers. Combine it with a small diff-and-pick-unit function to render human-friendly relative timestamps.

new Intl.RelativeTimeFormat(locales, options).format(value, unit)

Parameters

Parameter Purpose
locales BCP 47 tag(s)
numeric 'always' (3 days ago) | 'auto' (yesterday, today, tomorrow)
style 'long' | 'short' | 'narrow'
unit 'second','minute','hour','day','week','month','quarter','year'
.formatToParts() structured tokens for custom rendering

Examples

const rtf = new Intl.RelativeTimeFormat('en', {numeric:'auto'});
console.log(rtf.format(-1, 'day'));   // 'yesterday'
console.log(rtf.format(3, 'day'));    // 'in 3 days'

auto uses natural words

const rtf = new Intl.RelativeTimeFormat('en', {numeric:'always'});
console.log(rtf.format(-1, 'day')); // '1 day ago'

always numeric

const rtf = new Intl.RelativeTimeFormat('es', {style:'short'});
console.log(rtf.format(-2, 'hour')); // 'hace 2 h'

Spanish + short

function ago(d){const s=(d-Date.now())/1000; const [u,div]=Math.abs(s)<60?['second',1]:Math.abs(s)<3600?['minute',60]:Math.abs(s)<86400?['hour',3600]:['day',86400]; return new Intl.RelativeTimeFormat('en',{numeric:'auto'}).format(Math.round(s/div),u);} console.log(ago(new Date(Date.now()-5*60*1000))); // '5 minutes ago'

pick a unit by magnitude

Gotcha

The sign convention is future = positive, past = negative (opposite of getTimezoneOffset). The API does not pick a unit for you - divide the diff and choose 'second'/'minute'/'hour'/'day' yourself.

Related

← All JS Date methods · Math methods · Cron syntax