phploopsdatetimeforeachelapsed

PHP find the time elapsed since a date time inside a foreach loop


I'm looking fe a solution: i have a foreach loop (of posts) inside a slideshow and i need to retrieve the time elapsed since the publish date. I'm following this thread PHP How to find the time elapsed since a date time? and this is what i've done so far, but it doesn't work, it broke the slideshow or i got an error about $time variabe that can't be re decleared. Could someone help? Thanks.

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

Solution

  • Thanks to @Clément Malet to point me in the right direction, DateTime::diff helped me to get the solution:

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

    And the final output is like: Published: 10 hour and 25 minutes ago