Displaying time-related data in a human-readable format is a crucial part of enhancing user experience in modern web applications. Instead of showing raw date-time strings, using relative time descriptors like “yesterday”, “tomorrow”, or “2 minutes ago” can make your application much more intuitive. In this article, we will discuss how to display relative time descriptions using JavaScript.
Why Relative Time Descriptions?
Relative time descriptions help users instantly contextualize time-related information. For example, seeing “yesterday” is often more relatable than seeing “2023-10-14T14:20:00Z”. These descriptors can help reduce the cognitive load and improve engagement.
Using JavaScript to Display Relative Time
JavaScript provides various methods to manipulate dates and times. One of the simplest ways to handle relative times is by using libraries, but first, let’s explore how you can achieve this with vanilla JavaScript.
Vanilla JavaScript Solution
Here’s a basic implementation using JavaScript's native Date
object.
function timeAgo(date) {
const now = new Date();
const secondsPast = (now - date) / 1000;
if (secondsPast < 60) {
return `${Math.floor(secondsPast)} seconds ago`;
} else if (secondsPast < 3600) {
return `${Math.floor(secondsPast / 60)} minutes ago`;
} else if (secondsPast < 86400) {
return `${Math.floor(secondsPast / 3600)} hours ago`;
} else {
const day = date.getDate();
const month = date.getMonth() + 1; // months are zero-indexed
const year = date.getFullYear() === now.getFullYear() ? '' : date.getFullYear();
return `${day}/${month}/${year}`;
}
}
const myDate = new Date('2023-10-14');
console.log(timeAgo(myDate)); // Outputs: "x days ago" or the date format according to difference
This function covers transformations of seconds into minutes, minutes into hours, and handles days beyond a certain threshold by reverting back to a simple date format.
Using Intl.RelativeTimeFormat
API
For a more robust solution, consider using Intl.RelativeTimeFormat
, which is designed for internationalization and produces grammatically correct differences in many languages:
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
function getRelativeTime(date) {
const now = new Date();
const diff = now - date;
const seconds = Math.floor(diff / 1000);
if (seconds < 60) return rtf.format(-seconds, 'second');
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return rtf.format(-minutes, 'minute');
const hours = Math.floor(minutes / 60);
if (hours < 24) return rtf.format(-hours, 'hour');
const days = Math.floor(hours / 24);
return rtf.format(-days, 'day');
}
const anotherDate = new Date('2023-10-16');
console.log(getRelativeTime(anotherDate)); // Outputs: "in x days" or similar based on the current date
Using Intl.RelativeTimeFormat
simplifies the process considerably while adding flexibility and accuracy across different locales. The above usage allows your application to automatically adjust wording according to language-specific rules.
Handling Future Dates
It’s also important to consider handling future dates, such as “tomorrow” or “in two days”. The Intl.RelativeTimeFormat
handles these cases smoothly, providing intuitively correct results for future times as well.
Conclusion
Displaying relative time formats can enhance user interaction by making time-related data more integrated into users' mental models. You can implement this functionality using vanilla JavaScript for quick solutions or adopt Intl.RelativeTimeFormat
for more advanced needs. Regardless of the method chosen, making your application’s temporal data human-friendly is a step towards a better user experience.