Time Ago 函数 PHP 不工作?
Time Ago Function PHP Not Working?
出于某种原因,当我通过我的函数传递日期时间时,即使日期时间等于 2015-01-14,它也会返回“45 年前”17:27:13。
这是代码
函数:
function time_elapsed_string($ptime)
{
$etime = time() - $ptime;
if ($etime < 1)
{
return '0 seconds';
}
$a = array( 365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$a_plural = array( 'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach ($a as $secs => $str)
{
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
}
}
}
当我调用它时,我使用我的 MySQL 查询结果调用它,它显示为“2015-01-14 17:27:13”。
45 年前是 UNIX timestamp 的 0。检查您传递给函数的数据以确保其有效。
如果您传递 MySQL 日期字符串,time() - '2015-01-14 17:27:13'
现在大约等于 1421257297
,因为 (int)'2015-01-14 17:27:13'
变成 2015
。
更改函数的第一行,以便从秒中减去秒:
$etime = time() - strtotime($ptime);
出于某种原因,当我通过我的函数传递日期时间时,即使日期时间等于 2015-01-14,它也会返回“45 年前”17:27:13。
这是代码
函数:
function time_elapsed_string($ptime)
{
$etime = time() - $ptime;
if ($etime < 1)
{
return '0 seconds';
}
$a = array( 365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$a_plural = array( 'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach ($a as $secs => $str)
{
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
}
}
}
当我调用它时,我使用我的 MySQL 查询结果调用它,它显示为“2015-01-14 17:27:13”。
45 年前是 UNIX timestamp 的 0。检查您传递给函数的数据以确保其有效。
如果您传递 MySQL 日期字符串,time() - '2015-01-14 17:27:13'
现在大约等于 1421257297
,因为 (int)'2015-01-14 17:27:13'
变成 2015
。
更改函数的第一行,以便从秒中减去秒:
$etime = time() - strtotime($ptime);