Jump to content

timeago function giving wrong value


bravo14

Recommended Posts

Hi all

 

Trying to use a timeago function, however for a date and time for today of 2016-07-02 16:41:48 it is showing at 46 years ago.

 

below is the function

 

function ago($timestamp)
{
    $diff = time() - (int)$timestamp;
    //echo $diff;

    if ($diff == 0)
         return 'just now';

    $intervals = array
    (
        1                   => array('year',    31556926),
        $diff < 31556926    => array('month',   2628000),
        $diff < 2629744     => array('week',    604800),
        $diff < 604800      => array('day',     86400),
        $diff < 86400       => array('hour',    3600),
        $diff < 3600        => array('minute',  60),
        $diff < 60          => array('second',  1)
    );

     $value = floor($diff/$intervals[1][1]);
     return $value.' '.$intervals[1][0].($value > 1 ? 's' : '').' ago';
}

 

and this is how I am displaying it

 

echo '<span class="timeAgo">'.ago($row['date_time']).'</span>';
Link to comment
Share on other sites

The $intervals array is truly one of the weirdest pieces of code I've ever seen. Where do you got this from? It also seems you're trying to cast a timestamp string into a integer, somehow expecting it to (magically?) turn into a Unix timestamp. This makes no sense and will give you 2016 as Unix time, which was indeed 46 years ago.

 

I'd scrap the code and do it properly with the DateTime class. Yes, PHP can do date calculations. ;)

<?php

$timeIntervalAttributeNames = [
    'y' => 'year',
    'm' => 'month',
    'd' => 'day',
    'h' => 'hour',
    'i' => 'minute',
    's' => 'second',
];



$testTimestamp = '2016-07-02 16:41:48';
$testDateTime = DateTime::createFromFormat('Y-m-d G:i:s', $testTimestamp);

$now = new DateTime();
$diff = $now->diff($testDateTime);

$formattedDiff = '';
foreach ($timeIntervalAttributeNames as $attribute => $name)
{
    $val = $diff->$attribute;
    if ($val != 0)
    {
        $formattedDiff = $val.' '.$name.($val > 1 ? 's' : s);
        break;
    }
}

echo $formattedDiff;
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.