PHP How do I calculate relative time?
Possible Duplicate:
PHP: producing relative date/time from timestamps
Given a specific DateTime value, how do I display relative time, like
etc, etc...?
mysql_query("UPDATE users SET lastlogin = ".time()." WHERE id = ".$userID);
this may help you
function time_ago_en($time)
{
if(!is_numeric($time))
$time = strtotime($time);
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "age");
$lengths = array("60","60","24","7","4.35","12","100");
$now = time();
$difference = $now - $time;
if ($difference <= 10 && $difference >= 0)
return $tense = 'just now';
elseif($difference > 0)
$tense = 'ago';
elseif($difference < 0)
$tense = 'later';
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
$period = $periods[$j] . ($difference >1 ? 's' :'');
return "{$difference} {$period} {$tense} ";
}
Example
<?php
echp time_ago_en(time() - 300);
// 5 minutes ago
?>
strtotime
is a nice function
let me be more specific
strtotime(-5 days);
or
strtotime(-1 month);
There is an optional 2nd argument which is another time stamp of the time you want to start at, giving your relative
time. Why the downvote?
<?php
function relativeTime($time = false, $limit = 86400, $format = 'g:i A M jS') {
if (empty($time) || (!is_string($time) && !is_numeric($time))) $time = time();
elseif (is_string($time)) $time = strtotime($time);
$now = time();
$relative = '';
if ($time === $now) $relative = 'now';
elseif ($time > $now) $relative = 'in the future';
else {
$diff = $now - $time;
if ($diff >= $limit) $relative = date($format, $time);
elseif ($diff < 60) {
$relative = 'less than one minute ago';
} elseif (($minutes = ceil($diff/60)) < 60) {
$relative = $minutes.' minute'.(((int)$minutes === 1) ? '' : 's').' ago';
} else {
$hours = ceil($diff/3600);
$relative = 'about '.$hours.' hour'.(((int)$hours === 1) ? '' : 's').' ago';
}
}
return $relative;
}
?>
资源
链接地址: http://www.djcxy.com/p/58966.html下一篇: PHP如何计算相对时间?