CodeBlanks Logo Icon CodeBlanks

Intl.RelativeTimeFormat

JavaScript course · Expert · Lesson 57/63

Learn to format relative-time phrases like '3 days ago' with Intl.RelativeTimeFormat.

Intl.RelativeTimeFormat

Intl.RelativeTimeFormat formats relative time phrases like '3 days ago' or 'in 2 hours'. Pass a locale string to the constructor; the format method takes a number and a unit string. Units are: 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'. A negative number means 'ago', a positive one means 'in'. The numeric: 'auto' option uses 'yesterday' instead of '1 day ago' for some values.

Exercise Produce 'yesterday'

Create an Intl.RelativeTimeFormat for the 'tr-TR' locale. Set numeric to 'auto'. Call format with -1 and 'day', and assign the result to the yesterday variable.

Show example solution
1. Create with new Intl.RelativeTimeFormat('tr-TR', { numeric: 'auto' }).
2. Call .format(-1, 'day').
3. Assign to the yesterday variable.

Example solution:
const yesterday = new Intl.RelativeTimeFormat('tr-TR', { numeric: 'auto' }).format(-1, 'day');

The numeric and style options

Intl.RelativeTimeFormat has two important options. numeric defaults to 'always' and always shows a number: '1 day ago'. 'auto' uses special strings for some values: 'yesterday', 'today', 'tomorrow'. style takes three values: 'long' gives the full form ('day ago'), 'short' a short one ('da ago'), 'narrow' the shortest. A negative number means 'ago', a positive one 'in'. A wrong unit throws a RangeError.

Test yourself

  1. What does numeric: 'auto' do?

    • It only allows positive numbers
    • It changes the time zone
    • It shortens the output
    • It uses 'yesterday' instead of '1 day ago' for some values
    Show answer

    It uses 'yesterday' instead of '1 day ago' for some values — Correct. numeric 'auto' produces locale-specific short strings for some values.

  2. Add the day unit

    const rtf = new Intl.RelativeTimeFormat('en'); rtf.format(-3, '____');
    Show answer
    const rtf = new Intl.RelativeTimeFormat('en'); rtf.format(-3, 'day'');
  3. Match time units to their meaning

    year
    Year
    month
    Month
    day
    Day
    hour
    Hour

All lessons in Expert