14

relational-datetime.js

A JavaScript utility function for converting dates into human-readable relative time formats. Perfect for displaying timestamps in social media, chat apps, and activity feeds.

javascript utility

When building applications that display timestamps, developers often face the challenge of presenting time information in a user-friendly way. Raw timestamps like "2023-11-18T10:30:00Z" are not intuitive for users. Here's a JavaScript function that converts dates into human-readable relative time formats!

getRelationalDateTime Function

To convert dates into relative time formats, we can use the following JavaScript function:

export function getRelationalDateTime(dateString) {
  const date = new Date(dateString);
  const now = new Date();
 
  const diffMs = now.getTime() - date.getTime();
  const seconds = Math.floor(diffMs / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
 
  if (seconds < 60) return `${seconds} second${seconds !== 1 ? 's' : ''} ago`;
  if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`;
  if (hours < 24) return `${hours} hour${hours !== 1 ? 's' : ''} ago`;
  if (days === 1) return 'Yesterday';
 
  // Format as dd/mm/yyyy for older dates
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 0-based month
  const year = date.getFullYear();
 
  return `${day}/${month}/${year}`;
}

Step by step

The function works by:

  1. Converting input: Takes a date string and converts it to a Date object
  2. Calculating difference: Computes the time difference in milliseconds from current time
  3. Converting units: Transforms milliseconds into seconds, minutes, hours, and days
  4. Applying logic: Uses conditional statements to determine the most appropriate time format
  5. Formatting output: Returns human-readable strings with proper pluralization

Examples

// Example 1: Recent activity (seconds)
const recentTime = "2023-11-18T14:29:30Z";
console.log(getRelationalDateTime(recentTime));
// Output: "30 seconds ago"
 
// Example 2: Recent activity (minutes)
const fewMinutesAgo = "2023-11-18T14:25:00Z";
console.log(getRelationalDateTime(fewMinutesAgo));
// Output: "5 minutes ago"
 
// Example 3: Yesterday
const yesterday = "2023-11-17T14:30:00Z";
console.log(getRelationalDateTime(yesterday));
// Output: "Yesterday"
 
// Example 4: Older date
const oldDate = "2023-10-15T10:30:00Z";
console.log(getRelationalDateTime(oldDate));
// Output: "15/10/2023"

Use cases

This approach is particularly useful for:

  • Social media applications: Displaying post timestamps like "2 hours ago"
  • Chat applications: Showing message timestamps in conversation threads
  • Activity feeds: Indicating when actions or events occurred
  • Notification systems: Showing when alerts or updates happened
  • Content management: Displaying article publish times or last modified dates
  • E-commerce: Showing order timestamps and delivery updates

Key Features

  • Automatic time unit selection: Chooses the most appropriate unit based on the time difference
  • Human-readable output: Returns natural language that users can easily understand
  • Fallback to absolute dates: Shows dd/mm/yyyy format for older dates
  • Proper pluralization: Handles singular and plural forms correctly
  • Zero dependencies: Pure JavaScript implementation with no external libraries

The function is lightweight, efficient, and provides a clean solution for displaying relative time information that significantly improves user experience compared to raw timestamps.