note 83560 added to function.time

From: Date: Sun, 01 Jun 2008 05:06:14 +0000
Subject: note 83560 added to function.time
Groups: php.notes 
Request: Send a blank email to php-notes+get-140039@lists.php.net to get a copy of this message
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) /* * 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) */ ---- Server IP: 69.147.83.197 Probable Submitter: 67.99.175.226 ---- Manual Page -- http://www.php.net/manual/en/function.time.php Edit -- https://master.php.net/note/edit/83560 Del: integrated -- https://master.php.net/note/delete/83560/integrated Del: useless -- https://master.php.net/note/delete/83560/useless Del: bad code -- https://master.php.net/note/delete/83560/bad+code Del: spam -- https://master.php.net/note/delete/83560/spam Del: non-english -- https://master.php.net/note/delete/83560/non-english Del: in docs -- https://master.php.net/note/delete/83560/in+docs Del: other reasons-- https://master.php.net/note/delete/83560 Reject -- https://master.php.net/note/reject/83560 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#140039) next »