JavaScript

Format Relative Time

by @admin
10h ago
Apr 28, 2026
Public
Returns a human-readable relative time string ("3 days ago", "in 2 hours") using the Intl.RelativeTimeFormat API. Automatically selects the most appropriate unit (seconds, minutes, hours, days, weeks, months, years) based on the elapsed time. Fully localised — pass any BCP 47 locale.
JavaScript
function timeAgo(date, locale = 'en') {
  const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
  const diff = (new Date(date) - Date.now()) / 1000;
  const units = [
    ['year', 31536000], ['month', 2592000], ['week', 604800],
    ['day', 86400],     ['hour', 3600],     ['minute', 60], ['second', 1],
  ];
  for (const [unit, secs] of units) {
    if (Math.abs(diff) >= secs || unit === 'second') {
      return rtf.format(Math.round(diff / secs), unit);
    }
  }
}

// Usage
console.log(timeAgo(Date.now() - 3 * 86400 * 1000)); // "3 days ago"
console.log(timeAgo(Date.now() + 2 * 3600 * 1000));  // "in 2 hours"
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.