[英]PHP find the time elapsed since a date time inside a foreach loop
我正在寻找一种解决方案:我在幻灯片放映中有一个(帖子的)foreach循环,我需要检索自发布日期以来经过的时间。 我正在关注这个线程PHP如何查找自日期时间起经过的时间? 这是我到目前为止所做的事情,但是不起作用,它破坏了幻灯片放映,或者我遇到了有关$ time variabe的错误,无法清除。 有人可以帮忙吗? 谢谢。
<?php if(count($comments) > 0): ?>
<?php foreach($comments as $comment): ?>
<?php
$authorPicture = $comment['authorPicture'];
$author = $comment['author'];
$image = $comment['image'];
$message = $comment['message'];
$likes = $comment['likes'];
$type = $comment['type'];
$data = $comment['cacheDate'];
$time = substr($data, 0, -3); //need to do this to retrieve a correct Unix timestamp
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
?>
<div class="data"><?php echo 'event happened '.humanTiming($time).' ago'; ?></div>
<?php endforeach; ?>
<?php else: ?>
<h2>There are no comments yet</h2>
<?php endif; ?>
感谢@ClémentMalet指出正确的方向, DateTime :: diff帮助我获得了解决方案:
<?php foreach($comments as $comment): ?>
<?php
// foreach items
$data = $comment['cacheDate']; // this store a unix value like 1404992204999
// foreach items
<!-- html code -->
<div class="message">
<p class="data"><strong>Published: </strong>
<?php
$date1 = $data;
$date2 = time();
$subTime = $date1 - $date2;
$y = ($subTime/(60*60*24*365));
$d = ($subTime/(60*60*24))%365;
$h = ($subTime/(60*60))%24;
$m = ($subTime/60)%60;
echo $h." hour and " . $m." minutes"; // no need for years and days
?>
<strong>ago </strong>
</div>
<?php endforeach; ?>
<?php else: ?>
<h2>There are no comments yet</h2>
<?php endif; ?>
最终输出是: 发布: 10小时25分钟前
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.