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;
Edited by Jacques1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.