Intl relativeTime

Intl relativeTime

by Csaba Hellinger

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.12/dayjs.min.js"></script>

CSS

body {
  font-family: monospace;
}

JavaScript

// Dayjs is only used for numerical calculations
// Formatting is via Intl.
// Try changing the language, numeric, and style params below.

const relativeTime = new Intl.RelativeTimeFormat("en", { // "en", "en-US"
  localeMatcher: "best fit",
  numeric: "auto", // "auto"="yesterday", "always"="1d ago"
  style: "narrow", // "long"="seconds", "short"="sec.", "narrow"="s"
});

const units = ['year','month','day','hour','minute','second'];

const now = dayjs();

const dateToRelative = (date) => {
  for (const unit of units) {
    const diff = date.diff(now, unit);
    if (!diff) continue;
    return relativeTime.format(diff, unit);
  }
  return relativeTime.format(0, 'second');
};

const tests = [
  now.add(4, 'year'),  
  now.add(5, 'month'),  
  now.add(2, 'week'),  
  now.add(3, 'day'),  
  now.add(1, 'day'),    
  now.add(1, 'hour'),  
  now.add(35, 'minute'),
  now.add(12, 'second'),
  now,
  now.subtract(12, 'second'),
  now.subtract(35, 'minute'),
  now.subtract(1, 'hour'),  
  now.subtract(1, 'day'),  
  now.subtract(3, 'day'),  
  now.subtract(2, 'week'),  
  now.subtract(5, 'month'),  
  now.subtract(4, 'year'),  
];

document.body.innerText = tests
  .map(date => `${date.toISOString()}: ${dateToRelative(date)}`)
  .join('\n')