note 71342 added to function.time
| From: | tristan at trinicle dot net | Date: | Thu, 23 Nov 2006 10:10:18 +0000 |
| Subject: | note 71342 added to function.time | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-120018@lists.php.net to get a copy of this message | ||
Initially I was using Andrew's function to convert a timestamp into a formatted age. It has
issues with times greater than a day (div by 0). I also added recursion to produce a result similar
to "2 decades 6 months 3 weeks 2 days 6 hours 56 minutes 52 seconds" when input a
timestamp from 1986. Hopefully someone will find this useful.
<?php
public static function TimeAgo($timestamp){
// Store the current time
$current_time = time();
// Determine the difference, between the time now and the timestamp
$difference = $current_time - $timestamp;
// Set the periods of time
$periods = array("second", "minute", "hour", "day",
"week", "month", "year", "decade");
// Set the number of seconds per period
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
// Determine which period we should use, based on the number of seconds lapsed.
// If the difference divided by the seconds is more than 1, we use that. Eg 1 year / 1 decade =
0.1, so we move on
// Go from decades backwards to seconds
for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $difference /
$lengths[$val]) <= 1); $val--);
// Ensure the script has found a match
if ($val < 0) $val = 0;
// Determine the minor value, to recurse through
$new_time = $current_time - ($difference % $lengths[$val]);
// Set the current value to be floored
$number = floor($number);
// If required create a plural
if($number != 1) $periods[$val].= "s";
// Return text
$text = sprintf("%d %s ", $number, $periods[$val]);
// Ensure there is still something to recurse through, and we have not found 1 minute and 0
seconds.
if (($val >= 1) && (($current_time - $new_time) > 0)){
$text .= self::TimeAgo($new_time);
}
return $text;
}
?>
----
Server IP: 203.202.10.60
Probable Submitter: 203.214.116.132
----
Manual Page -- http://www.php.net/manual/en/function.time.php
Edit -- https://master.php.net/note/edit/71342
Del: integrated -- https://master.php.net/note/delete/71342/integrated
Del: useless -- https://master.php.net/note/delete/71342/useless
Del: bad code -- https://master.php.net/note/delete/71342/bad+code
Del: spam -- https://master.php.net/note/delete/71342/spam
Del: non-english -- https://master.php.net/note/delete/71342/non-english
Del: in docs -- https://master.php.net/note/delete/71342/in+docs
Del: other reasons-- https://master.php.net/note/delete/71342
Reject -- https://master.php.net/note/reject/71342
Search -- https://master.php.net/manage/user-notes.php