Borislav Hadzhiev
Last updated: Jan 22, 2022
Check out my new book
To convert a timestamp to relative time:
Intl.RelativeTimeFormat()
constructor.format()
method on the constructor.format
method formats the value according to the provided options.function relativeDays(timestamp) { const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto', }); const oneDayInMs = 1000 * 60 * 60 * 24; const daysDifference = Math.round( (timestamp - new Date().getTime()) / oneDayInMs, ); return rtf.format(daysDifference, 'day'); } // (Today is 22nd Jan, 2022 // 👇️ 7 days ago console.log(relativeDays(new Date('2022-01-15').getTime())); // 👇️ 2 days ago console.log(relativeDays(new Date('2022-01-20').getTime())); // 👇️ yesterday console.log(relativeDays(new Date('2022-01-21').getTime())); // 👇️ today console.log(relativeDays(new Date().getTime())); // 👇️ in 113 days console.log(relativeDays(new Date('2022-05-15').getTime()));
The
Intl.RelativeTimeFormat()
constructor creates a Intl.RelativeTimeFormat
object, on which we can call the
format
method.
Intl.RelativeTimeFormat()
constructor is the locale.The locale can be a string or array of BCP 27 language tag strings.
The second parameter is an options object.
The numeric
property on the object has 2 possible values:
always
(default) - e.g. 1 day ago
.auto
- e.g. yesterday
. The auto
value allows to not always have to use
numeric values in the output and looks more natural in certain cases.The format
method takes 2 parameters:
value
to use in the internationalized relative time message.unit
to use in the message. Possible values are: year
, quarter
,
month
, week
, day
, hour
, minute
and second
.In the example, we passed day
as the unit
to the format
method.
The getTime method returns the number of milliseconds elapsed between 1st of January, 1970 00:00:00 and the given date.
We subtracted the current timestamp from the passed in timestamp and converted the result from milliseconds to days.
The function returns a string, formatted as: 2 days ago
, in 5 days
,
yesterday
, etc.