note 75004 modified in function.time by danbrown
| From: | danbrown@php.net | Date: | Sun, 20 Jul 2008 04:15:59 +0000 |
| Subject: | note 75004 modified in function.time by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142125@lists.php.net to get a copy of this message | ||
Time difference both forward and backward, based on tristan's TimeAgo() function :)
<?php
function timeDiff($timestamp){
$now = time();
//If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = 'away' : $action = 'ago';
switch($action) {
case 'away':
$diff = $timestamp - $now;
break;
case 'ago':
default:
// Determine the difference, between the time now and the timestamp
$diff = $now - $timestamp;
break;
}
// 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);
// Go from decades backwards to seconds
for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $diff /
$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 = $now - ($diff % $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]);
return $text . $action;
}
?>
If anyone knows of an easier way to do this, please comment.
--was--
Time difference both forward and backward, based on tristan's TimeAgo() function :)
function timeDiff($timestamp){
$now = time();
//If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = 'away' : $action = 'ago';
switch($action) {
case 'away':
$diff = $timestamp - $now;
break;
case 'ago':
default:
// Determine the difference, between the time now and the timestamp
$diff = $now - $timestamp;
break;
}
// 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);
// Go from decades backwards to seconds
for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $diff /
$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 = $now - ($diff % $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]);
return $text . $action;
}
If anyone knows of an easier way to do this, please comment.
http://php.net/manual/en/function.time.php