note 83560 deleted from function.time by aidan

From: Date: Wed, 15 Apr 2009 16:07:01 +0000
Subject: note 83560 deleted from function.time by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153334@lists.php.net to get a copy of this message
Note Submitter: Santosh Patnaik ---- This function formats an elapsed time or a time-difference value by distributing the value in seconds in to years, months, weeks, etc. (akin to using varying numbers of currency notes and coins of different denominations for the same amount of money) <?php /* * Formatted time-difference between $t1 and $t2 (seconds) * The difference in seconds is distributed into years, months, etc. as specified by $format. * $format is a string containing characters y, f, w, d, h, m or s, for years, months, weeks, days, hours, minutes or seconds, resp. * Output is an array containing keys y, f, etc., with the numerical values. * Values are negative if $t1 is more than $t2. */ function FormatTimeDiff($t1, $t2=null, $format='yfwdhms'){ $t2 = $t2 === null ? time() : $t2; $s = abs($t2 - $t1); $sign = $t2 > $t1 ? 1 : -1; $out = array(); $left = $s; $format = array_unique(str_split(preg_replace('[^yfwdhms]', '', strtolower($format)))); $format_count = count($format); $a = array('y'=>31556926, 'f'=>2629744, 'w'=>604800, 'd'=>86400, 'h'=>3600, 'm'=>60, 's'=>1); $i = 0; foreach($a as $k=>$v){ if(in_array($k, $format)){ ++$i; if($i != $format_count){ $out[$k] = $sign * (int)($left / $v); $left = $left % $v; }else{ $out[$k] = $sign * ($left / $v); } }else{ $out[$k] = 0; } } return $out; } print_r(FormatTimeDiff(1, 86402)); print_r(FormatTimeDiff(1, 86402, 'hms')); // distribute into hours, minutes and seconds only print_r(FormatTimeDiff(1, 86402, 'ds')); // distribute into days and minutes only print_r(FormatTimeDiff(86402, 1, 'm')); // distribute into only minutes /* Output: Array([y]=>0 [f]=>0 [w]=>0 [d]=>1 [h]=> 0 [m]=>0 [s]=>1) Array([y]=>0 [f]=>0 [w]=>0 [d]=>0 [h]=>24 [m]=>0 [s]=>1) Array([y]=>0 [f]=>0 [w]=>0 [d]=>1 [h]=> 0 [m]=>0 [s]=>1) Array([y]=>0 [f]=>0 [w]=>0 [d]=>0 [h]=> 0 [m]=>-1440.01666667 [s]=>0) */ ?>

« previous php.notes (#153334) next »