# General Translation Knowledge Base: How do I format "3 days ago" in JavaScript?
URL: https://generaltranslation.com/en-GB/kb/relative-time-format.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: Use JavaScript's built-in Intl.RelativeTimeFormat, which formats a number and a unit as relative time for any locale, including words like yesterday and the right plural form. It doesn't pick the unit, so add a small helper that chooses seconds, minutes, hours, or days from the difference between two dates.
Category: Locale Formatting
Last updated: 2026-11-23
Authors: Kevin Wu
Published: 2026-11-23

Building &quot;3 days ago&quot; by hand with `` `${n} days ago` `` works in English only. Other languages put the number in a different place (&quot;hace 3 días&quot;, &quot;3 日前&quot;), use words instead of numbers (&quot;yesterday&quot;, &quot;vorgestern&quot;), and change the noun with the count: Russian says &quot;3 дня назад&quot; but &quot;5 часов назад&quot;. Every modern browser and Node.js ships the data to get this right in [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat).

## How `Intl.RelativeTimeFormat` works

Create a formatter for a locale, then call `format(value, unit)`. Negative values are in the past and positive values are in the future:

```js
const rtf = new Intl.RelativeTimeFormat('en');

rtf.format(-3, 'day');  // "3 days ago"
rtf.format(3, 'day');   // "in 3 days"
rtf.format(-1, 'day');  // "1 day ago"
```

The unit is one of `second`, `minute`, `hour`, `day`, `week`, `month`, `quarter`, or `year`, and the plural spellings (`days`) work too. Anything else, such as `decade`, throws a `RangeError`.

## Say &quot;yesterday&quot; instead of &quot;1 day ago&quot;

The default, `numeric: 'always'`, always prints a number. Set `numeric: 'auto'` to get the words people actually use:

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

rtf.format(-1, 'day');  // "yesterday"
rtf.format(0, 'day');   // "today"
rtf.format(1, 'day');   // "tomorrow"
rtf.format(-1, 'year'); // "last year"
rtf.format(-3, 'day');  // "3 days ago"
```

Most interfaces want `'auto'`. Use `'always'` where the number itself matters, such as an audit log.

## The same call in other languages

These are the outputs from Node.js 24 with `numeric: 'auto'` for yesterday and the default for the rest:

| Locale | -1 day    | -3 days        | -5 hours        | +2 weeks            |
| ------ | --------- | -------------- | --------------- | ------------------- |
| `en`   | yesterday | 3 days ago     | 5 hours ago     | in 2 weeks          |
| `es`   | ayer      | hace 3 días    | hace 5 horas    | dentro de 2 semanas |
| `de`   | gestern   | vor 3 Tagen    | vor 5 Stunden   | in 2 Wochen         |
| `fr`   | hier      | il y a 3 jours | il y a 5 heures | dans 2 semaines     |
| `ja`   | 昨日        | 3 日前           | 5 時間前           | 2 週間後               |
| `ar`   | أمس       | قبل 3 أيام     | قبل 5 ساعات     | خلال أسبوعين        |
| `pl`   | wczoraj   | 3 dni temu     | 5 godzin temu   | za 2 tygodnie       |
| `ru`   | вчера     | 3 дня назад    | 5 часов назад   | через 2 недели      |

Word order, plural forms, and the special words all come from the Unicode CLDR data built into the runtime. Arabic &quot;two weeks&quot; is a single dual word, أسبوعين, with no digit, which no string template would produce.

## Shorter styles for tight layouts

`style` controls the width. `long` is the default:

```js
new Intl.RelativeTimeFormat('en', { style: 'short' }).format(-3, 'month');  // "3 mo. ago"
new Intl.RelativeTimeFormat('en', { style: 'narrow' }).format(-3, 'month'); // "3mo ago"
```

Short and narrow forms vary by language and are not always shorter, so check them in your target locales before relying on them to fit a fixed width.

## Pick the unit from two dates

`Intl.RelativeTimeFormat` formats a value you give it. It does not look at two dates and decide that 26 hours is &quot;yesterday&quot;. That step is yours:

```js title="timeAgo.js"
const UNITS = [
  ['year', 60 * 60 * 24 * 365],
  ['month', 60 * 60 * 24 * 30],
  ['week', 60 * 60 * 24 * 7],
  ['day', 60 * 60 * 24],
  ['hour', 60 * 60],
  ['minute', 60],
  ['second', 1],
];

export function timeAgo(date, locale, now = new Date()) {
  const seconds = Math.round((date.getTime() - now.getTime()) / 1000);
  const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });

  // Use the largest unit that fits at least once
  for (const [unit, size] of UNITS) {
    if (Math.abs(seconds) >= size || unit === 'second') {
      return rtf.format(Math.round(seconds / size), unit);
    }
  }
}
```

With `now` set to noon UTC on 23 November 2026:

```js
timeAgo(new Date('2026-11-23T11:59:30Z'), 'en', now); // "30 seconds ago"
timeAgo(new Date('2026-11-23T09:00:00Z'), 'en', now); // "3 hours ago"
timeAgo(new Date('2026-11-22T12:00:00Z'), 'es', now); // "ayer"
timeAgo(new Date('2026-11-20T12:00:00Z'), 'ru', now); // "3 дня назад"
timeAgo(new Date('2026-11-23T14:00:00Z'), 'en', now); // "in 2 hours"
```

Months and years here are approximate (30 and 365 days), which is fine for &quot;posted 2 months ago&quot;. When the exact calendar boundary matters, such as &quot;last month&quot; meaning the previous calendar month, compute the difference with a date library or `Temporal` instead.

## Use one reference time in server-rendered apps

`timeAgo` depends on `now`. In a server-rendered React app the server renders &quot;59 seconds ago&quot;, the browser renders &quot;1 minute ago&quot; a moment later, and React reports a hydration mismatch. Compute `now` once on the server and pass it to the client, or render relative times only on the client after hydration. (See [Why do dates cause a React hydration mismatch?](/kb/date-hydration-mismatch)).

Relative times also go stale on a page that stays open. Re-render them on an interval, such as every minute, if readers keep the page open for long.

## Keep relative times out of the translated sentence

A sentence like &quot;Updated 3 days ago&quot; has two parts: the translated words and the formatted time. Translate the sentence with a placeholder and format the time separately, so one translation serves every value. With [ICU message format](/kb/icu-message-format) that is `Updated {when}`, and the formatter fills in `when`.

General Translation&#39;s [`<RelativeTime>`](/docs/react/reference/components/relative-time) component does both steps in React. Pass it a `Date` and it picks the unit and formats it with `Intl.RelativeTimeFormat` for the active language; inside [`<T>`](/docs/react/reference/components/t), the sentence is translated once and the time stays a variable:

```tsx
import { T, RelativeTime } from 'gt-next';

export function LastUpdated({ updatedAt, now }) {
  return (
    <T>
      {/* baseDate pins the reference time so server and client agree */}
      <p>Updated <RelativeTime baseDate={now}>{updatedAt}</RelativeTime></p>
    </T>
  );
}
```

[`<RelativeTime>`](/docs/react/reference/components/relative-time) also takes an explicit `value` and `unit`, such as `<RelativeTime value={3} unit="day" />` for &quot;in 3 days&quot;, and defaults to `numeric: 'auto'`. The value is formatted locally and never sent for translation.

## Browser support

`Intl.RelativeTimeFormat` is [supported in every current browser](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat#browser_compatibility) and in Node.js with full ICU data, which official Node.js builds include. `Intl.RelativeTimeFormat.supportedLocalesOf(['fr', 'xx'])` tells you which of your locales the runtime has data for.

## Key takeaways

* `Intl.RelativeTimeFormat` handles word order, plural forms, and words like &quot;yesterday&quot; for every locale.
* Set `numeric: 'auto'` for natural wording, and `style` for shorter forms.
* It formats a number and a unit; a small helper picks the unit from two dates.
* Pass the same reference time to the server and the browser, or format after hydration.
* Translate the sentence around the time once and insert the formatted time as a variable.

## Related questions

- [How do I format numbers, dates and currencies for each locale?](https://generaltranslation.com/en-GB/kb/format-numbers-dates-currencies.mdx): Format each value when the page renders, using the reader's locale and JavaScript's Intl API, and keep it out of the translated sentence. General Translation's `<Num>`, `<Currency>`, `<DateTime>` and `<RelativeTime>` components do both inside a `<T>`, so one translation serves every value.
- [How do I handle plurals in React?](https://generaltranslation.com/en-GB/kb/how-to-handle-plurals-in-react.mdx): Handle plurals in React by giving each language one sentence per plural form and picking it with that language's plural rules, since English has 2 forms, Russian has 4 and Arabic has 6. General Translation's `<Plural>` component in gt-react and gt-next takes your source forms, and General Translation generates the forms each target language needs.
- [Why do dates cause a React hydration mismatch?](https://generaltranslation.com/en-GB/kb/date-hydration-mismatch.mdx): The server and the browser format the same date differently when they run in different time zones or default locales, so the HTML React hydrates doesn't match the client render. Pass an explicit locale and timeZone to every date format, or render the date only on the server.
- [What is ICU message format?](https://generaltranslation.com/en-GB/kb/icu-message-format.mdx): ICU message format is a syntax for one translatable string that holds variables, plurals, select choices, and ordinals, such as {count, plural, one {# file} other {# files}}. Each language keeps the CLDR plural categories it needs: English uses one and other, while Polish adds few and many.

## Previous and next questions

- Previous question: [How do I give AI translation enough context for software strings?](https://generaltranslation.com/en-GB/kb/ai-translation-context.mdx)
- Next question: [How do I translate gendered text in an app?](https://generaltranslation.com/en-GB/kb/translate-gendered-text.mdx)

## Sitemap

See the [Knowledge Base sitemap](https://generaltranslation.com/en-GB/kb/sitemap.md) for every article.
