amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.58k stars 236 forks source link

Distance formatter #1313

Closed ubersan closed 2 months ago

ubersan commented 2 months ago

Is your feature request related to a problem? Please describe.

I would like to display the duration, i.e. distance between two dates. It seems that currently the closest match is the relativeTime, however this returns the a) the duration with the ago suffix and b) for small durations doesn't display the number, but already sth like Now/Just now.

I tried to check the docs and options, but didn't find a way to achieve this result with the current API

Describe the solution you'd like

I would like to have something like the following

import {useFormatter} from 'next-intl';

function Component() {
  const format = useFormatter();
  const start = new Date('2020-11-20T08:30:00.000Z');
  const shortEnd = new Date('2020-11-20T08:30:02.000Z');
  const longEnd = new Date('2020-11-20T09:33:00.000Z');

  // This will render '2 seconds'
  format.duration(start, shortEnd);

  // This will render '1 hour'
  format.duration(start, longEnd);
}

Describe alternatives you've considered

Alternatively also an option for the existing relativeTime could be considered, such as

format.relativeTime(start, {now: end, asDuration: true})
amannn commented 2 months ago

You're probably looking for Intl.DurationFormat. We'll likely add support to next-intl once this API has reasonably good support in JS runtimes, in the meantime you can consider using a polyfill.

I've added this to the list in https://github.com/amannn/next-intl/issues/774 in order to track support for this, many thanks for the report!

ubersan commented 2 months ago

ah I see, thanks, I will check it out!