note 75743 added to function.time
| From: | rspenc29 at gmail dot com | Date: | Thu, 14 Jun 2007 01:33:39 +0000 |
| Subject: | note 75743 added to function.time | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-127464@lists.php.net to get a copy of this message | ||
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
----
Server IP: 69.147.83.197
Probable Submitter: 76.49.110.133
----
Manual Page -- http://www.php.net/manual/en/function.time.php
Edit -- https://master.php.net/note/edit/75743
Del: integrated -- https://master.php.net/note/delete/75743/integrated
Del: useless -- https://master.php.net/note/delete/75743/useless
Del: bad code -- https://master.php.net/note/delete/75743/bad+code
Del: spam -- https://master.php.net/note/delete/75743/spam
Del: non-english -- https://master.php.net/note/delete/75743/non-english
Del: in docs -- https://master.php.net/note/delete/75743/in+docs
Del: other reasons-- https://master.php.net/note/delete/75743
Reject -- https://master.php.net/note/reject/75743
Search -- https://master.php.net/manage/user-notes.php