note 75492 added to function.time

From: Date: Fri, 01 Jun 2007 20:26:56 +0000
Subject: note 75492 added to function.time
Groups: php.notes 
Request: Send a blank email to php-notes+get-127109@lists.php.net to get a copy of this message
Improvement on top of shdowhawk at gmail dot com: 1. Calculate the time difference (from start to end) 2. Time can be provided as formatted (e.g. 2005-04-02 12:11:10) or integer (12233455). 3. Provide a short display, e.g. 12h 3m 23s if (!function_exists('timeDiff')){ function timeDiff($starttime, $endtime, $detailed=false, $short = true){ if(! is_int($starttime)) $starttime = strtotime($starttime); if(! is_int($endtime)) $endtime = strtotime($endtime); $diff = ($starttime >= $endtime ? $starttime - $endtime : $endtime - $starttime); # Set the periods of time $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade"); $lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600); if($short){ $periods = array("s", "m", "h", "d", "m", "y"); $lengths = array(1, 60, 3600, 86400, 2630880, 31570560); } # Go from decades backwards to seconds $i = sizeof($lengths) - 1; # Size of the lengths / periods in case you change them $time = ""; # The string we will hold our times in while($i >= 0) { if($diff > $lengths[$i-1]) { # if the difference is greater than the length we are checking... continue $val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1. That means one minute. 130 / 60 = 2. Two minutes.. etc $time .= $val . ($short ? '' : ' ') . $periods[$i-1] . ((!$short && $val > 1) ? 's ' : ' '); # The value, then the name associated, then add 's' if plural $diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information } $i--; } return $time; } } ---- Server IP: 64.71.164.2 Probable Submitter: 144.92.91.250 ---- Manual Page -- http://www.php.net/manual/en/function.time.php Edit -- https://master.php.net/note/edit/75492 Del: integrated -- https://master.php.net/note/delete/75492/integrated Del: useless -- https://master.php.net/note/delete/75492/useless Del: bad code -- https://master.php.net/note/delete/75492/bad+code Del: spam -- https://master.php.net/note/delete/75492/spam Del: non-english -- https://master.php.net/note/delete/75492/non-english Del: in docs -- https://master.php.net/note/delete/75492/in+docs Del: other reasons-- https://master.php.net/note/delete/75492 Reject -- https://master.php.net/note/reject/75492 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#127109) next »