【问题标题】:PHP find the time elapsed since a date time inside a foreach loopPHP在foreach循环中查找自日期时间以来经过的时间
【发布时间】:2014-07-19 14:38:17
【问题描述】:

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

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

【问题讨论】:

  • 你想达到什么目的? DateTime::diff 可以帮助你php.net/manual/en/datetime.diff.php
  • 非常感谢!!!我找到了这个例子,我解决了look here !!!
  • 基于该示例,您如何从检索到的日期中删除破折号?谢谢
  • 如果您还有其他值得一提的问题,请创建一个新问题。

标签: php loops datetime foreach elapsed


【解决方案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; ?>

最终输出如下:Published: 10 小时 25 分钟

【讨论】:

    猜你喜欢
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多