此问题基于另一个有权获得的StackOverFlow question 在PHP中将时间戳转换为时间,例如1天前,2天前......
勾选的answer无法解释但显示此功能:
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';
}
}
}
我的时间格式为 YYYY-MM-DD HH-MM-SS ,例如: 2015-01-21 19:23:09 。
我的尝试:
echo $target_time = time_elapsed_string(strtotime("2015-01-21 19:23:09"));
它给出了:
45年前。任何时候也给45岁。我不知道这个功能是如何工作的,但是感谢任何帮助。
答案 0 :(得分:2)
这可以使用PHP的DateTime
和DateDiff
对象轻松完成
$datetime1 = new DateTime();
$datetime2 = new DateTime("2015-01-21 19:23:09");
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
有关要传递的格式字符串的完整说明,请查看documentation。
答案 1 :(得分:0)
我从http://timeago.yarp.com找到了一个简单有效的解决方案:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://timeago.yarp.com/jquery.timeago.js"></script>
<script>
jQuery(document).ready(function() {
jQuery("abbr.timeago").timeago();
});
</script>
<abbr class="timeago" title="2015-01-21T21:30:00"></abbr>