brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Intl.RelativeTimeFormat writes "3 days ago" in any language

Javascript
~/tips/tip-javascript-intl-relativetimeformat-nl

const rtf = new Intl.RelativeTimeFormat("nl", { numeric: "auto" });

Formats a number and a unit as relative time in a chosen language, without a library.

Moment-style libraries are a lot of weight for the sentence “3 days ago”. The browser already knows how to say it, in Dutch too.

const rtf = new Intl.RelativeTimeFormat("nl", { numeric: "auto" });
rtf.format(-3, "day");  // "3 dagen geleden"
rtf.format(-1, "day");  // "gisteren"
rtf.format(2, "hour");  // "over 2 uur"

A negative value gives the past (“ago”), a positive value the future (“in …”). The second argument is the unit.

The numeric option has two values. "always" is the default and always writes a number, like “1 day ago”. "auto" uses words such as “yesterday” when the language has them. style can be "long", "short" or "narrow", so you can fit a small card. Switch the first argument to "en" or "es" and the same code speaks that language.

MDN lists it as widely available across browsers since September 2020.

The caveat is that it only formats. You still have to work out the number and the unit yourself, for example by subtracting two dates and deciding whether to say hours or days. Rounding is yours too. It also writes in the exact words of the locale data your browser or Node version ships, so I check the output for the languages I care about instead of assuming it matches what I would say.

Further reading: MDN: Intl.RelativeTimeFormat

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link