note 75743 deleted from function.time by danbrown
| From: | danbrown@php.net | Date: | Sun, 20 Jul 2008 04:14:34 +0000 |
| Subject: | note 75743 deleted from function.time by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142121@lists.php.net to get a copy of this message | ||
Note Submitter: rspenc29 at gmail dot com
----
To further expand on shdowhawk's timeDiff function I added a small but important feature
function timeDiff($timestamp,$detailed=false,$n = 0){
$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 >= $n) {
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;
}
}
Now you can specify where you want to stop. Example
timeDiff($yourtimestamp,1,4); //Stops after days (no hours, minutes, seconds)
timeDiff($yourtimestamp,1,5); //Stops after hours