note 78677 deleted from function.time by aidan

From: Date: Wed, 15 Apr 2009 16:05:05 +0000
Subject: note 78677 deleted from function.time by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153331@lists.php.net to get a copy of this message
Note Submitter: stack-phpnotes at landstander dot com ---- My modification and enhancements to the timeDiff() function last updated by sean sullivan. The rewrite was done to add a couple new optional parameters but I also got a bump in performance. On a completely personal preference level I changed the month and year second values with ones I got from Google searches. Written and tested with 5.2.0. Options include to = time(); date to compute the range to parts = 1; number of parts to display max precision = 'second'; lowest part to compute to distance = TRUE; include the 'ago' or 'away' bit separator = ', '; separates the parts <?php function timeDiff($time, $opt = array()) { // The default values $defOptions = array( 'to' => 0, 'parts' => 1, 'precision' => 'second', 'distance' => TRUE, 'separator' => ', ' ); $opt = array_merge($defOptions, $opt); // Default to current time if no to point is given (!$opt['to']) && ($opt['to'] = time()); // Init an empty string $str = ''; // To or From computation $diff = ($opt['to'] > $time) ? $opt['to']-$time : $time-$opt['to']; // An array of label => periods of seconds; $periods = array( 'decade' => 315569260, 'year' => 31556926, 'month' => 2629744, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1 ); // Round to precision if ($opt['precision'] != 'second') $diff = round(($diff/$periods[$opt['precision']])) * $periods[$opt['precision']]; // Report the value is 'less than 1 ' precision period away (0 == $diff) && ($str = 'less than 1 '.$opt['precision']); // Loop over each period foreach ($periods as $label => $value) { // Stitch together the time difference string (($x=floor($diff/$value))&&$opt['parts']--) && $str.=($str?$opt['separator']:'').($x.' '.$label.($x>1?'s':'')); // Stop processing if no more parts are going to be reported. if ($opt['parts'] == 0 || $label == $opt['precision']) break; // Get ready for the next pass $diff -= $x*$value; } $opt['distance'] && $str.=($str&&$opt['to']>$time)?' ago':' away'; return $str; } ?> Usage: $span = timeDiff($when); or $span = timeDiff($when, array('parts' => 3));

« previous php.notes (#153331) next »