PHP查找自foreach循环内的日期时间起经过的时间

时间:2014-07-19 14:38:18

标签: php loops datetime foreach elapsed

我正在寻找一个解决方案:我在幻灯片中有一个foreach循环(帖子),我需要检索自发布日期以来经过的时间。我正在关注这个帖子PHP How to find the time elapsed since a date time?,这是我迄今为止所做的,但它不起作用,它打破了幻灯片,或者我得到了一个关于$ time变量的错误,可以& #39;重新被删除。有人可以帮忙吗?感谢。

<?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; ?>

1 个答案:

答案 0 :(得分:1)

感谢@Clément Malet指出了正确的方向,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分钟以前