Convert a Timestamp to Relative Time (time ago) in JS


Borislav Hadzhiev

Last updated: Jan 22, 2022


Check out my new book

Convert a Timestamp to Relative Time (time ago) in JS #

To convert a timestamp to relative time:

  1. Create an object using the Intl.RelativeTimeFormat() constructor.
  2. Use the format() method on the constructor.
  3. The 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.

The first parameter we passed to the 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:

  1. a value to use in the internationalized relative time message.
  2. the 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.

For the first parameter, we calculated the difference in days between the passed in timestamp and the current date.

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 result can be either a negative (timestamps in the past) or a positive (timestamps in the future) integer.

The function returns a string, formatted as: 2 days ago, in 5 days, yesterday, etc.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.