Course contentsShow
← JavaScript
Lesson 1656 of 2,72335. Standard Library and Built-insFree lesson

Formatting Relative Time Values

Use the format method to convert numeric values and units into localized relative time strings like 'in 3 days'.

Formatting Relative Time Values

You'll learn how to convert numeric time differences into human-readable relative phrases like "in 3 days" or "5 hours ago" using the format() method.

Core Idea

Once you've created a RelativeTimeFormat instance, you use its format() method to transform a numeric value and a time unit into a localized string. The method takes two arguments: a number (positive for future, negative for past) and a unit (like "day", "hour", "month").

Think of it like a translation service: you give it raw data ("3" and "day"), and it returns a culturally appropriate phrase based on the locale you configured.

How It Works

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

// Future times use positive numbers
console.log(rtf.format(3, 'day'));    // "in 3 days"
console.log(rtf.format(1, 'hour'));   // "in 1 hour"

// Past times use negative numbers
console.log(rtf.format(-2, 'week'));  // "2 weeks ago"
console.log(rtf.format(-1, 'day'));   // "yesterday" (with 'auto')

// Different locales produce different output
const rtfFr = new Intl.RelativeTimeFormat('fr');
console.log(rtfFr.format(5, 'month')); // "dans 5 mois"

Valid Units

You can use: "year", "quarter", "month", "week", "day", "hour", "minute", "second".

Note that the format() method doesn't calculate anything for you—it just formats what you give it. If you pass 90 minutes, it won't convert to hours; it will say "in 90 minutes."

Key Takeaway: The format() method transforms a numeric value and time unit into a locale-aware relative time string, with positive numbers indicating future and negative numbers indicating past.