note 90989 added to function.date
| From: | luck dot lil dot leprechaun at gmail dot com | Date: | Tue, 19 May 2009 22:53:29 +0000 |
| Subject: | note 90989 added to function.date | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-155761@lists.php.net to get a copy of this message | ||
This is an easily extendable and pretty way to output human-readable date differences such as
"1 day 2 hours ago", "6 months ago", "3 years 7 months 14 days 1 hour 4
minutes 16 seconds" etc etc.
Change "$levels = 2;" to whatever you want. A value of 1 will limit to only one number in
the result ("3 days ago"). A value of 3 would result in up to three ("3 days 1 hour 2
minutes ago")
It can be used in the following ways:
echo compare_dates($start_date,$end_date);
echo compare_dates($end_date,$start_date);
echo compare_dates($start_date); //end date will be assumed as time();
<?php
function compare_dates($date1, $date2 = time())
{
$blocks = array(
array('name'=>'year','amount' => 60*60*24*365 ),
array('name'=>'month','amount' => 60*60*24*31 ),
array('name'=>'week','amount' => 60*60*24*7 ),
array('name'=>'day','amount' => 60*60*24 ),
array('name'=>'hour','amount' => 60*60 ),
array('name'=>'minute','amount' => 60 ),
array('name'=>'second','amount' => 1 )
);
$diff = abs($date1-$date2);
$levels = 2;
$current_level = 1;
$result = array();
foreach($blocks as $block)
{
if ($current_level > $levels) {break;}
if ($diff/$block['amount'] >= 1)
{
$amount = floor($diff/$block['amount']);
if ($amount>1) {$plural='s';} else {$plural='';}
$result[] = $amount.' '.$block['name'].$plural;
$diff -= $amount*$block['amount'];
}
}
return implode(' ',$result).' ago';
}
?>
----
Server IP: 208.69.120.35
Probable Submitter: 216.158.164.3
----
Manual Page -- http://www.php.net/manual/en/function.date.php
Edit -- https://master.php.net/note/edit/90989
Del: integrated -- https://master.php.net/note/delete/90989/integrated
Del: useless -- https://master.php.net/note/delete/90989/useless
Del: bad code -- https://master.php.net/note/delete/90989/bad+code
Del: spam -- https://master.php.net/note/delete/90989/spam
Del: non-english -- https://master.php.net/note/delete/90989/non-english
Del: in docs -- https://master.php.net/note/delete/90989/in+docs
Del: other reasons-- https://master.php.net/note/delete/90989
Reject -- https://master.php.net/note/reject/90989
Search -- https://master.php.net/manage/user-notes.php