Easy To Read PHP Date Function
Tutorial by James of
Bandit.co.nz™
Copyright James Nisbet 2005 ~ 2007
7th November 2006
So I wanted a little function to output an easy to read but inaccurate date. I came up with the following little function;
<?php
function ezDate($d) {
$ts = time() - strtotime(str_replace("-","/",$d));
// check if date is in the past or future
if($ts>0) { $when = ' ago'; } else { $ts = (int)str_replace("-","",$ts); }
if($ts>31536000) { $val = round($ts/31536000,0); $typ = 'year'; }
else if($ts>2419200) { $val = round($ts/2419200,0); $typ = 'month'; }
else if($ts>604800) { $val = round($ts/604800,0); $typ = 'week'; }
else if($ts>86400) { $val = round($ts/86400,0); $typ = 'day'; }
else if($ts>3600) { $val = round($ts/3600,0); $typ = 'hour'; }
else if($ts>60) { $val = round($ts/60,0); $typ = 'minute'; }
else { $val = $ts; $typ = 'second'; }
if($val!=1) $typ .= 's';
return $val.' '.$typ.$when;
}
?>
Then I use it as follows;
<?php
echo 'My birthday was '.ezDate('2006-09-07 18:42:00');
?>
Which would output (at the time of posting this);
My birthday was 2 months ago.
I add an acronym tag around the output also, so my users can mouse-over for the exact date.
For example:
<?php
echo 'My birthday was <acronym title="2006-09-07 18:42:00">'.ezDate('2006-09-07 18:42:00').'</acronym>';
?>
Have fun. If you have any issues, please
drop me a line.
If you liked this tutorial please
tell a friend.