Categories
JavaScript Answers

How to convert timestamp to relative time with JavaScript?

Spread the love

Sometimes, we want to convert timestamp to relative time with JavaScript.

In this article, we’ll look at how to convert timestamp to relative time with JavaScript.

How to convert timestamp to relative time with JavaScript?

To convert timestamp to relative time with JavaScript, we use the Intl.RelativeTimeFormat constructor.

For instance, we write

const units = [
  ["year", 31536000000],
  ["month", 2628000000],
  ["day", 86400000],
  ["hour", 3600000],
  ["minute", 60000],
  ["second", 1000],
];

const rtf = new Intl.RelativeTimeFormat("en", { style: "narrow" });
const relatime = (elapsed) => {
  for (const [unit, amount] of units) {
    if (Math.abs(elapsed) > amount || unit === "second") {
      return rtf.format(Math.round(elapsed / amount), unit);
    }
  }
};

to create the rtf RelativeTimeFormat object.

Then we define the relatime function that takes the elapsed relative in milliseconds.

And then we use a for-of loop to loop through the units array.

In the loop, we check if the absolute elapsed amount is bigger than amount or the unit is 'second'.

If either are true, then we return the formatted elapsed time we get with rtf.format to format the elapsed time to the unit.

Conclusion

To convert timestamp to relative time with JavaScript, we use the Intl.RelativeTimeFormat constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *