Some nifty PHP date/time functions


I wrote two date/time functions in PHP that I was really pleased with so thought I'd post them.

  • string friendlydate ( numeric or string $input )
    Return value is a day in relation to today in the format "Today", "Yesterday", "Wednesday", "March 2", or "November 7, 2007".
  • string howlong ( numeric or string $a, numeric or string $b ) Return value is the approximate length of time between two dates, $a and $b.  Examples are "4 seconds ago", "1 minute from now", "1 hour ago", "yesterday", "2 months ago", "1 year ago".


function friendlydate($input) {
 if (!is_numeric($input)) $input = strtotime($input);
 if (date("Ymd", $input) == date("Ymd", time())) return "Today";
 if (date("Ymd", $input) == date("Ymd", time()-60*60*24)) return "Yesterday";
 if ($input > time()-60*60*24*6) return date("l", $input);
 if (date("Y", $input) == date("Y", time())) return date("F jS", $input);
 return date("F jS, Y", $input);
 }
function howlong($a=0, $b=0) {
 if (!is_numeric($a)) $a = strtotime($a); if (!is_numeric($b)) $b = strtotime($b);
 if ($a == 0) $a = time(); if ($b == 0) $b = time();
 if ($a == $b) return "at the same time";
 if ($a > $b) { $aa = $b; $b = $a; $a = $aa; $q = "away"; } else { $q = "ago"; }
 $value = $b-$a;
 if ($value == 1) return "1 second $q";
 if ($value < 60) return "$value seconds $q";
 $value /= 60;
 if (round($value) == 1) return "1 minute $q";
 if ($value < 60) return round($value) . " minutes $q";
 $value /= 60;
 if (round($value) == 1) return "1 hour $q";
 if ($value < 24) return round($value) . " hours $q";
 $value /= 24;
 if (round($value) == 1) if ($q == "ago") return "yesterday"; else return "tomorrow";
 if ($value < 31) return round($value) . " days $q";
 $value /= 31;
 if (round($value) == 1) return "1 month $q";
 if ($value < 12) return round($value) . " months $q";
 $value /= 12;
 if (round($value) == 1) return "1 year $q";
 return round($value) . " years $q";
 }

 

If you would like a reply to your comment, you must leave your email address! We receive dozens of questions every month from people who don't leave us with any way to contact them, so we have no choice but to ignore the question. We try to reply to as many questions as we can, if we know the email address of the person who asked the question. Thanks in advance for writing in :)

Allowed HTML: <b>, <i>, <em>, <strong>. All other < and > will be replaced with &lt; and &gt;.