Course contentsShow
← JavaScript
Lesson 2221 of 2,72346. InternationalizationFree lesson

The format() Method

Using format(value, unit) to generate relative time strings like 'in 5 minutes' or 'yesterday'.

The format() Method

You'll learn how to turn numeric time differences into friendly, locale-aware phrases like "in 3 days" or "2 hours ago."

What format() Does

The format() method on Intl.RelativeTimeFormat transforms a numeric value and time unit into a human-readable relative time string. Instead of displaying "86400 seconds" or doing manual calculations, you simply pass the number and unit—JavaScript handles the grammar, pluralization, and locale conventions for you.

Core Syntax

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

console.log(rtf.format(-1, 'day'));    // "yesterday"
console.log(rtf.format(5, 'minute'));  // "in 5 minutes"
console.log(rtf.format(0, 'hour'));    // "this hour"
console.log(rtf.format(-2, 'week'));   // "2 weeks ago"

The Two Parameters

  1. value (number): How many units ahead (positive) or behind (negative). Zero represents "now."
  2. unit (string): One of 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', or 'second'.

The method combines these to produce grammatically correct output. Negative values mean the past; positive values mean the future.

Style Variations

The numeric option (set during instance creation) affects output:

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

console.log(auto.format(-1, 'day'));    // "yesterday"
console.log(always.format(-1, 'day'));  // "1 day ago"

Use 'auto' for natural phrases like "yesterday"; use 'always' for consistent numeric output.

Key Takeaway: The format(value, unit) method transforms raw time differences into locale-appropriate relative phrases, handling grammar and special cases like "yesterday" automatically.