note 75233 deleted from function.time by danbrown
| From: | danbrown@php.net | Date: | Sun, 20 Jul 2008 04:15:16 +0000 |
| Subject: | note 75233 deleted from function.time by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142124@lists.php.net to get a copy of this message | ||
Note Submitter: shdowhawk at gmail dot com
----
I modified the timeDiff scripts from what other people just wrote. I added my little twist onto it
=)
Basically... now you can add in a detailed option. By default it is turned off, so we get the .. 1
hour ago .. or .. 2 weeks away.
By calling timeDiff($timestamp,1) ... or timeDiff($timeStamp,true) .. we can now get a detailed
count down. Ex: 1 hour 7 minutes 47 seconds ago
function timeDiff($timestamp,$detailed=false){
$now = time();
#If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = 'away' : $action = 'ago';
$diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);
# 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);
# 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 ." ". $periods[$i-1].($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--;
}
# Basic error checking.
if($time == "") {
return "Error-- Unable to calculate time.";
} else {
return $time.$action;
}
}