What is Intl.RelativeTimeFormat?
You'll learn what Intl.RelativeTimeFormat is and how it formats time differences in human-friendly, localized ways.
The Core Idea
Intl.RelativeTimeFormat is a built-in JavaScript API that converts numeric time differences into natural language phrases like "in 3 days," "2 hours ago," or "last week." Instead of manually building these strings (and translating them), you provide a number and a time unit, and the formatter handles localization for you.
Think of it as a translator between "time math" and "how humans talk about time." When you tell someone "I'll see you in 5 days," you're doing relative time formatting in your head. This API does that programmatically, respecting different languages and cultural conventions.
Why It Matters
Different languages express relative time differently. English says "3 days ago," but Spanish might say "hace 3 días." Without Intl.RelativeTimeFormat, you'd need translation files and complex logic. This API makes it automatic.
What You Work With
You create a formatter instance (similar to Intl.NumberFormat or Intl.DateTimeFormat), specify a locale and options, then call format() with:
- A numeric value (positive for future, negative for past)
- A time unit (like
'day','hour','week')
The formatter returns localized strings like "yesterday," "in 2 months," or "3 minutes ago" based on your inputs.
The Big Picture
This API completes JavaScript's internationalization toolkit. You've already seen how to format numbers, currencies, and absolute dates. Now you can format relative time differences, making your apps feel natural to users worldwide.
Key Takeaway: Intl.RelativeTimeFormat transforms numeric time differences and units into localized, human-readable phrases like "in 3 days" or "2 hours ago," automatically handling language-specific conventions.