note 97294 added to function.date-diff

From: Date: Mon, 12 Apr 2010 22:06:01 +0000
Subject: note 97294 added to function.date-diff
Groups: php.notes 
Request: Send a blank email to php-notes+get-168179@lists.php.net to get a copy of this message
eugene's function below was what I was looking for, but it was immediately obvious it could be done better. Here's my version: I haven't included months or years, but you only need to add a couple more array entries if you want those. <?php function timediff($start,$end='NOW',$precision=2) { $num = array(0,60,3600,86400,604800); $txt = array('sec','min','hour','day','week'); $time = strtotime($end) - strtotime($start); $return = ''; for ($i = count($num)-1;$i >= 0;$i--) { if (($time >= $num[$i]) && ($precision > 0)) { $next = ($i == 0) ? $time : round(($time - ($time % $num[$i])) / $num[$i]); $return .= $next.' '.$txt[$i]; if ($next > 1) { $return .= 's'; } $return .= ' '; if ($i != 0) { $time = ($time % $num[$i]); } $precision--; } } return $return; } echo timediff('2010-04-12 17:07:00'),"<br/>\n"; echo timediff('2000-01-01 00:00:00','2000-01-01 00:01:31'),"<br/>\n"; // 1 min 31 secs echo timediff('2000-01-01 00:00:00','2000-01-02 02:02:02'),"<br/>\n"; // 1 day 2 hours echo timediff('2000-01-01 00:00:00','2000-06-06 06:06:06',3),"<br/>\n"; // 22 weeks 3 days 6 hours echo timediff('2000-01-01 00:00:00','2003-03-03 03:03:03',5),"<br/>\n"; // 165 weeks 2 days 3 hours 3 mins 3 secs ?> ---- Server IP: 69.147.83.197 Probable Submitter: 89.240.71.116 ---- Manual Page -- http://www.php.net/manual/en/function.date-diff.php Edit -- https://master.php.net/note/edit/97294 Del: integrated -- https://master.php.net/note/delete/97294/integrated Del: useless -- https://master.php.net/note/delete/97294/useless Del: bad code -- https://master.php.net/note/delete/97294/bad+code Del: spam -- https://master.php.net/note/delete/97294/spam Del: non-english -- https://master.php.net/note/delete/97294/non-english Del: in docs -- https://master.php.net/note/delete/97294/in+docs Del: other reasons-- https://master.php.net/note/delete/97294 Reject -- https://master.php.net/note/reject/97294 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168179) next »