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));
----
Server IP: 69.147.83.197
Probable Submitter: 66.193.249.107
----
Manual Page -- http:/
/www.php.net/manual/en/function.time.php
Edit -- https://master
.php.net/note/edit/78677
Del: integrated -- h
ttps://master.php.net/note/delete/78677/integrated
Del: useless -- http
s://master.php.net/note/delete/78677/useless
Del: bad code -- htt
ps://master.php.net/note/delete/78677/bad+code
Del: spam -- https:/
/master.php.net/note/delete/78677/spam
Del: non-english --
https://master.php.net/note/delete/78677/non-english
Del: in docs -- http
s://master.php.net/note/delete/78677/in+docs
Del: other reasons-- https://mast
er.php.net/note/delete/78677
Reject -- https://mast
er.php.net/note/reject/78677
Search -- https://
master.php.net/manage/user-notes.php
--
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php
|