Course contentsShow
← Web Development
Lesson 2765 of 2,98249. Dates, Times, and Numbers on the WebFree lesson

Relative Time Formatting with Intl.RelativeTimeFormat

Display relative times like '2 days ago' or 'in 3 hours' using Intl.RelativeTimeFormat with numeric and style options.

Relative Time Formatting with Intl.RelativeTimeFormat

You'll learn how to display human-friendly relative times like "2 days ago" or "in 3 hours" using JavaScript's built-in internationalization API.

What Is Intl.RelativeTimeFormat?

Instead of showing absolute timestamps like "May 15, 2024 at 3:30 PM," users often prefer relative expressions: "posted 5 minutes ago" or "meeting in 2 hours." Intl.RelativeTimeFormat is the native browser API that handles this formatting automatically, respecting the user's locale.

Think of it like having a multilingual assistant who knows how to say "yesterday" in every language—you just provide the number and unit, and it handles the rest.

Basic Usage

Create a formatter instance, then call format() with a numeric value and a time unit:

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

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

Negative values indicate past times; positive values indicate future times.

Key Options

numeric: Controls whether to use numeric or natural language:

  • 'always': "1 day ago" (always shows numbers)
  • 'auto': "yesterday" (uses words when natural)

style: Adjusts verbosity:

  • 'long': "3 hours ago" (default)
  • 'short': "3 hr. ago"
  • 'narrow': "3h ago"
const shortRtf = new Intl.RelativeTimeFormat('en', { 
  style: 'short' 
});

console.log(shortRtf.format(-5, 'minute'));  // "5 min. ago"

Key Takeaway: Intl.RelativeTimeFormat transforms numeric time differences into localized, human-readable relative time strings with control over format style and whether to prefer natural language like "yesterday" over numeric expressions.