Loading

  • Contents
  • Images
  • Styles
  • Scripts

How to convert a date/time string into a human-readable format like “2 hours ago”, “1 week ago” in PHP?

This PHP function time_ago($timestamp) is used to convert a date/time string into a human-readable format like “2 hours ago”, “1 week ago”, etc. Let’s break it down step by step:

Function Definition

function time_ago($timestamp)
  • Takes one input: $timestamp (a string, like '2025-04-06 10:00:00').

Step 1: Calculate Time Difference

$current_time = time(); // Current UNIX timestamp
$time_diff = $current_time - strtotime($timestamp); // Difference in seconds
  • time() returns the current time in UNIX timestamp format (seconds since Jan 1, 1970).
  • trtotime($timestamp) converts the input date/time string into UNIX timestamp.
  • So $time_diff is how many seconds have passed since that timestamp.

Step 2: Convert Seconds into Other Units

$seconds = $time_diff;
$minutes = round($seconds / 60);
$hours = round($seconds / 3600);
$days = round($seconds / 86400);
$weeks = round($seconds / 604800);
$months = round($seconds / 2629440);
$years = round($seconds / 31553280);

This section converts the time difference into:

  • Minutes (60 seconds),
  • Hours (3600 seconds),
  • Days (86400 seconds),
  • Weeks (7 days),
  • Months (approx. 30.44 days),
  • Years (approx. 365.24 days).

Step 3: Return Human-Readable Text

This part checks the time range and returns the correct string:

if ($seconds <= 60) {
  return "Just now";
} elseif ($minutes <= 60) {
  return ($minutes == 1) ? "1 minute ago" : "$minutes minutes ago";
}

So the function returns:

  • “Just now” if under 60 seconds.
  • “1 minute ago” / “X minutes ago” if within 1 hour.
  • “X hours ago”, “X days ago”, “X weeks ago”, “X months ago”, or “X years ago”, depending on how long ago it was.

The Complete Code

function time_ago($timestamp) { 
  $current_time = time(); 
  $time_diff = $current_time - strtotime($timestamp); 
  $seconds = $time_diff; 
  $minutes = round($seconds / 60); 
  $hours = round($seconds / 3600); 
  $days = round($seconds / 86400); 
  $weeks = round($seconds / 604800); 
  $months = round($seconds / 2629440); 
  $years = round($seconds / 31553280); 
  if ($seconds <= 60) { 
    return "Just now"; 
  } elseif ($minutes <= 60) { 
    return ($minutes == 1) ? "1 minute ago" : "$minutes minutes ago"; 
  } elseif ($hours <= 24) { 
    return ($hours == 1) ? "1 hour ago" : "$hours hours ago"; 
  } elseif ($days <= 7) { 
    return ($days == 1) ? "1 day ago" : "$days days ago"; 
  } elseif ($weeks <= 4.3) { 
    return ($weeks == 1) ? "1 week ago" : "$weeks weeks ago"; 
  } elseif ($months <= 12) { 
    return ($months == 1) ? "1 month ago" : "$months months ago"; 
  } else { 
    return ($years == 1) ? "1 year ago" : "$years years ago"; 
  } 
}

Example

If current time is 2025-04-06 12:00:00 and you pass:

time_ago("2025-04-06 11:45:00");

Then:

  • Time difference = 15 minutes
  • Output = “15 minutes ago”