0

i have a span tag which has array data like

<?php echo " <span >".$comments_array[$j]['posted_time']."</span> "; ?>

and it echo's time of the comment as 2014-04-11 05:07:52

now i have a function that display the time in the format of x hrs ago,

below is the function

 define("SECOND", 1);
 define("MINUTE", 60 * SECOND);
 define("HOUR", 60 * MINUTE);
 define("DAY", 24 * HOUR);
 define("MONTH", 30 * DAY);
 function relTime($time)
 {   
$now       = new DateTime;
$dateObj   = new DateTime($dt);
$diff      = (array) $now->diff($dateObj);
$diff['w'] = floor($diff['d'] / 7);
$diff['d'] -= $diff['w'] * 7;

$tokens = array(
    'y' => 'year',
    'm' => 'month',
    'w' => 'week',
    'd' => 'day',
    'h' => 'hour',
    'i' => 'minute',
    's' => 'second'
);

foreach ($tokens as $unit => &$text)
{
    if ($diff[$unit])
    {
        $text = sprintf(
            '%s %s%s', 
            $diff[$unit], $text, ($diff[$unit] > 1 ? 's' : '')
        );
    }
    else
    {
        unset($tokens[$unit]);
    }
}

return array_shift($tokens);
 } 

now how can i call that function and echo that time in desired format

help me please

stacky
  • 311
  • 1
  • 6
  • 26

1 Answers1

0

There's a better and cleaner way to achieve this. Here's a function, which, given a date/time string and a format string, will return the difference from now in the desired format.

function getDatetimeDifference($datetime, $format) {
    $datetime_obj = new DateTime($datetime);
    $now = new DateTime();
    $difference = date_diff($now, $datetime_obj);
    $result = $difference->format($format);
    return $result;
}

Here's a use case:

echo getDatetimeDifference(
    '2013-04-11 10:35:33', 
    '%R%a days, %h hours, %i minutes, %s seconds ago'
);

// Outputs "-364 days, 23 hours, 55 minutes, 10 seconds ago"

If you want to work with the total amount of hours since that time, you will fare better if you work with timestamps, since you can easily substract the difference and then divide it by 3600 to get the time difference in hours.

Keep in mind that the DateTime objects will overflow if you don't pass the appropriate format - for example, if you use the above function to get only the hours between now and the last year, you will get 23 as result. My advice - use a similar function, pass a suitable format that you can parse later in tokens, and eliminate left to right tokens until you reach a non-negative value.

Cheers.

NorthBridge
  • 639
  • 8
  • 20