Calculating Relative Time in JavaScript
Nathan
Posted on September 5, 2021
Have you ever seen something like "4 days ago" or "11 minutes ago" in an app or on a website?
This is sometimes called a relative time. It might be used in a messaging app to indicate when a message was received, or in a social media app to indicate when a post was published. But those are just a few examples.
Anyway, this post will show you how you can calculate relative time in JavaScript!
Consider the following snippet, which will return the current Unix timestamp:
const date = new Date();
const timestamp = date.getTime();
This gives us the number of miliseconds that have passed since January 1, 1970.
Usually, Unix timestamps are presented in seconds. Seconds are easier to work with, and they're adequately precise for many common use cases.
So, let's convert that timestamp to seconds:
const seconds = Math.floor(timestamp / 1000);
Next, let's also create an old timestamp that we can compare the current timestamp to:
const oldTimestamp = seconds - 86400;
Finally, we can compare the two timestamps and produce a human-readable output:
const difference = seconds - oldTimestamp;
let output = ``;
if (difference < 60) {
// Less than a minute has passed:
output = `${difference} seconds ago`;
} else if (difference < 3600) {
// Less than an hour has passed:
output = `${Math.floor(difference / 60)} minutes ago`;
} else if (difference < 86400) {
// Less than a day has passed:
output = `${Math.floor(difference / 3600)} hours ago`;
} else if (difference < 2620800) {
// Less than a month has passed:
output = `${Math.floor(difference / 86400)} days ago`;
} else if (difference < 31449600) {
// Less than a year has passed:
output = `${Math.floor(difference / 2620800)} months ago`;
} else {
// More than a year has passed:
output = `${Math.floor(difference / 31449600)} years ago`;
}
console.log(output);
I've found this solution sufficient for most use cases on the web and within apps.
If oldTimestamp
is 3 days before seconds
(the current timestamp), then output
will return "3 days ago", and so on.
This snippet will only work if the difference between the two timestamps is greater than zero, so make sure you're subtracting them in the correct order!
Easy i18n for relative times
I also want to mention that there is a handy relative time formatting utility in JavaScript's built-in Internationalization API:
const formatter = new Intl.RelativeTimeFormat(`en`, { style: `narrow`, });
const relativeTime = formatter.format(-5, `day`);
console.log(relativeTime);
// Output: "5 days ago"
Essentially, if you wanted to get really fancy, you could combine the timestamp comparison snippet with the RelativeTimeFormat
object to automatically translate the human-readable output.
In the example I provided, the output is in English. But you can change en
to any subtag from the long list of supported languages, such as es
(Spanish).
Conclusion
Working with timestamps in JavaScript (and many other programming languages) can be time-consuming and tedious.
I hope this snippet helped you out with automatically comparing the value of an old timestamp relative to the current time!
Posted on September 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.