note 97294 deleted from function.date-diff by danbrown

From: Date: Mon, 12 Apr 2010 22:06:47 +0000
Subject: note 97294 deleted from function.date-diff by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-168180@lists.php.net to get a copy of this message
Note Submitter: deepcut ---- 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 ?>

« previous php.notes (#168180) next »