我知道这个问题之前已被问过2-3次了,而且我正在使用我在其中一个答案(check it here)中找到的函数,但它似乎并没有正常工作我,我在评论中问过,但没有得到任何答复,所以我在这里开了一个新问题。以下是从日期时间(mysql类型)获取纯文本日期/时间的代码。
function getElapsedTime($time_stamp)
{
$ts = convert_datetime($time_stamp);
$time_stamp = $ts;
$time_difference = strtotime('now') - $time_stamp;
if ($time_difference >= 60 * 60 * 24 * 365.242199)
{
return get_time_ago_string($time_stamp, 60 * 60 * 24 * 365.242199, 'year');
}
elseif ($time_difference >= 60 * 60 * 24 * 30.4368499)
{
return get_time_ago_string($time_stamp, 60 * 60 * 24 * 30.4368499, 'month');
}
elseif ($time_difference >= 60 * 60 * 24 * 7)
{
return get_time_ago_string($time_stamp, 60 * 60 * 24 * 7, 'week');
}
elseif ($time_difference >= 60 * 60 * 24)
{
return get_time_ago_string($time_stamp, 60 * 60 * 24, 'day');
}
elseif ($time_difference >= 60 * 60)
{
return get_time_ago_string($time_stamp, 60 * 60, 'hour');
}
elseif($time_difference <= 60)
{
return get_time_ago_string($time_stamp, 60, 'minute');
}
}
function get_time_ago_string($time_stamp, $divisor, $time_unit)
{
$time_difference = strtotime("now") - $time_stamp;
$time_units = floor($time_difference / $divisor);
settype($time_units, 'string');
if ($time_units === '0')
{
return 'less than 1 ' . $time_unit . ' ago';
}
elseif ($time_units === '1')
{
return '1 ' . $time_unit . ' ago';
}
else
{
return $time_units . ' ' . $time_unit . 's ago';
}
}
function convert_datetime($str) {
list($date, $time) = explode(' ', $str);
list($year, $month, $day) = explode('-', $date);
list($hour, $minute, $second) = explode(':', $time);
$timestamp = mktime($hour, $minute, $second, $month, $day, $year);
return $timestamp;
}
我已经添加了一个函数convert_datetime(),它将mysql日期时间日期转换为时间戳,因为我认为函数getElapsedTime()期望时间戳,因为当我传递正常的日期时间日期(mysql格式)时,它无法正常工作。所以现在,我将mysql datetime传递给getElapsedTime()并使用convert_datetime()函数将其转换为时间戳,并使用它来获取字符串。
但是当预计日期将返回“分钟”或“秒”时,其返回负值。例如,它返回“-182分钟前”为“2013-05-23 15:59:58”..
有人知道如何完成它吗?
答案 0 :(得分:2)
使用PHP的DateTime类更简单: -
function time_ago($time_stamp)
{
$time = new DateTime($time_stamp);
$now = new DateTime();
$diff = $now->diff($time);
return $diff->format("%h hours, %i minutes ago");
}
$diff
是DateInterval的实例。
如果您愿意,可以使用以下方式指定$time_stamp
中收到的format: -
$time = DateTime::createFromFormat('Your format here');
答案 1 :(得分:1)
//尝试此功能
function time_ago($ptime) {
$ptime = strtotime($ptime);
if ($ptime) {
$etime = time() - $ptime;
if ($etime < 1)
return 'few seconds';
$a = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($a as $secs => $str) {
$d = $etime / $secs;
if ($d >= 1) {
$r = round($d);
return $r . ' ' . $str . ($r > 1 ? 's' : '') . '';
}
}
}
return '0';
}
//用法
echo time_ago('2013-05-23 15:59:58');
echo time_ago(date('Y:m:d H:i:s'));
//输出
43 minutes
few seconds