0Pricing
JavaScript Academy · Lesson

Relative Time and Plurals

Use RelativeTimeFormat and PluralRules.

Intl.RelativeTimeFormat

Intl.RelativeTimeFormat produces phrases like "3 days ago" or "in 2 hours" in the user's language.

const rtf = new Intl.RelativeTimeFormat("en-US");
console.log(rtf.format(-1, "day")); // "1 day ago"
console.log(rtf.format(2, "hour"));  // "in 2 hours"

Negative for Past, Positive for Future

The sign of the number sets the direction: negative is past, positive is future.

const rtf = new Intl.RelativeTimeFormat("en-US");
console.log(rtf.format(-3, "week")); // "3 weeks ago"
console.log(rtf.format(5, "minute")); // "in 5 minutes"

All lessons in this course

  1. Formatting Numbers and Currency
  2. Formatting Dates and Times
  3. Relative Time and Plurals
  4. Locale-Aware Sorting
← Back to JavaScript Academy