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

Common Patterns: Calculating Time Differences

Converting Date differences into appropriate units for RelativeTimeFormat formatting.

Common Patterns: Calculating Time Differences

You'll learn: How to convert raw Date differences into the right units and signs for Intl.RelativeTimeFormat.

The Challenge

RelativeTimeFormat expects you to provide both a numeric value and a unit (like 'day' or 'hour'). It doesn't automatically calculate "how many days ago" something happened—you must do that math yourself. The pattern is straightforward: subtract timestamps, convert to the appropriate unit, and determine the sign.

Core Pattern

  1. Get the difference in milliseconds:
    Subtract the target date from the current date (Date.now() - pastDate.getTime()).

  2. Convert to the desired unit:
    Divide by the milliseconds-per-unit constant (e.g., 1000 * 60 * 60 * 24 for days).

  3. Apply the correct sign:
    Past events are negative, future events are positive. Since we subtracted pastDate from now, past dates yield positive milliseconds—so negate the result for format().

  4. Round appropriately:
    Use Math.round() for nearest unit, Math.floor() for "full units elapsed," or Math.ceil() depending on your needs.

Example Flow

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

const now = Date.now();
const yesterday = new Date('2025-06-14T12:00:00Z');

const diffMs = now - yesterday.getTime();
const diffDays = Math.round(diffMs / (1000 * 60 * 60 * 24));

// Negate because it's in the past
console.log(rtf.format(-diffDays, 'day')); // "yesterday"

Choosing Units

Pick the largest sensible unit: if diffDays < 7, use 'day'; if < 30, use 'week'; otherwise 'month' or 'year'. This keeps output human-friendly ("2 weeks ago" vs "14 days ago").

Key Takeaway:
Calculate time differences by subtracting timestamps, converting to your chosen unit, negating for past events, and rounding—then pass the result and unit name to RelativeTimeFormat.format().