SyntaxStudy
Sign Up
JavaScript Intermediate 5 min read

Relative Time Formatting

Relative Time Formatting

Intl.RelativeTimeFormat formats dates as "3 hours ago", "in 2 days" — localized for any language.

Example
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

rtf.format(-1, "day");    // "yesterday"
rtf.format(-3, "hour");   // "3 hours ago"
rtf.format(2, "day");     // "in 2 days"
rtf.format(1, "month");   // "next month"

// Smart relative time function
function timeAgo(date) {
  const diff = (new Date(date) - Date.now()) / 1000;
  const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
  if (Math.abs(diff) < 60) return rtf.format(Math.round(diff), "second");
  if (Math.abs(diff) < 3600) return rtf.format(Math.round(diff/60), "minute");
  if (Math.abs(diff) < 86400) return rtf.format(Math.round(diff/3600), "hour");
  return rtf.format(Math.round(diff/86400), "day");
}
Pro Tip

Intl.RelativeTimeFormat handles pluralization automatically — "1 hour ago" vs "3 hours ago" without any conditionals.