Sling Academy
Home/JavaScript/Displaying Relative Time Descriptions (“Yesterday”, “Tomorrow”) in JavaScript

Displaying Relative Time Descriptions (“Yesterday”, “Tomorrow”) in JavaScript

Last updated: December 12, 2024

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.

Next Article: Scheduling Future Tasks Based on Specific Dates and Times in JavaScript

Previous Article: Handling Leap Years and Edge Cases in JavaScript Date Calculations

Series: Date and Time in JavaScript: Basic to Advanced Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration