Skip to content
Johnu Marattil

← Lab

"5 minutes ago" timestamps

Johnu Marattilui engineering1 min

A raw timestamp like 2023-11-18T10:30:00Z means nothing to most people. Feeds, chats and notifications read better with “5 minutes ago”. This function does that for recent times and falls back to a plain date for anything older than yesterday.

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}`;
}

How it works

  1. Parse the input into a Date.
  2. Take the difference from now, in milliseconds.
  3. Convert that into seconds, minutes, hours and days.
  4. Return the largest unit that fits, with the plural handled.
  5. Past yesterday, return dd/mm/yyyy.

Examples

Assuming it is now 2023-11-18 14:30 UTC:

getRelationalDateTime('2023-11-18T14:29:30Z'); // "30 seconds ago"
getRelationalDateTime('2023-11-18T14:25:00Z'); // "5 minutes ago"
getRelationalDateTime('2023-11-17T14:30:00Z'); // "Yesterday"
getRelationalDateTime('2023-10-15T10:30:00Z'); // "15/10/2023"

Where it fits

Post timestamps, chat threads, activity feeds, notifications, article dates and order updates. It is plain JavaScript with no dependencies.

Filed under ui engineering