-3

So i found this code from the link bellow and it worked fine like 2 days ago but then just stops working. when i gave it the time from mysql CURRENT TIMESTAMP it just outputs 8, 7 or 6 hours no matter how long it has been. if anyone knows how to improve this or a better way to do the function please submit it here or give me a link to it. I have tried it on php 5.6 and php 7 but neither fix it.

example:

$time = 2017-09-11 17:10:51

input:

time_elapsed_string($time);

output:

5 hours ago

#function from https://stackoverflow.com/questions/1416697/converting-timestamp-to-time-ago-in-php-e-g-1-day-ago-2-days-ago
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
Nick W
  • 9
  • 5
  • Please provide timestamps you have entered, which result in strange outputs. And provide the output how you would expect it to be. – Philipp Palmtag Sep 11 '17 at 09:38
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. – Script47 Sep 11 '17 at 09:40

1 Answers1

0

when i gave it the time from mysql CURRENT TIMESTAMP it just outputs 8, 7 or 6 hours no matter how long it has been

This sounds like your MySQL server and your PHP server are running in different timezones.

The code sample you provided does not account for timezones and instead simply calculates the amount of local time difference between the given date and the current time.

To account for different timezones you can use DateTime::setTimezone: http://php.net/manual/en/datetime.settimezone.php

Example:

$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n"; // 2000-01-01 00:00:00+12:00

$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n"; // 2000-01-01 01:45:00+13:45
Mike S
  • 1,636
  • 7
  • 11