PHP date_ago function!

Thought I posted this labourious piece of code that changes a unix timestamp into a “xx <seconds|minutes|hours|days|weeks|months> ago” date format.

<?php

function date_ago($time) {
  if ($time < 60) {
    $num = $time;
    $unit = 'second';
  }
  elseif ($time < 3600) {
    $num = floor($time / 60);
    $unit = 'minute';
  }
  elseif ($time < 86400) {
    $num = floor($time / 3600);
    $unit = 'hour';
  }
  elseif ($time < 604800) {
    $num = floor($time / 86400);
    $unit = 'day';
  }
  elseif ($time < 2419200) {
    $num = floor($time / 604800);
    $unit = 'week';
  }
  elseif ($time < 29030400) {
    $num = floor($time / 2419200);
    $unit = 'month';
  }
  return $num . ' ' . $unit . ($num > 1 ? 's' : '');
}

3 Responses

  1. I wonder where I’ve seen that before ;)

    Kamil - November 26th, 2009 at 11:26 pm
  2. Geez! I wonder… :P

    admin - November 27th, 2009 at 2:34 am
  3. I hope this snippet is MIT or BSD Licensed!

    Kamil - November 27th, 2009 at 11:49 am

Leave a Reply