2

I found this as an example for a time elapsed string. I have a weird thing going on, when I post it from my local web server it goes to my remote database, It will show the time since on my local webserver correctly, but when you post from my live webserver it comes back as 12 hours ago when it was just posted. (That's when it's updated from my remote server to my remote database that are hosted on the webserver. Find it weird that my local one would give me the correct time while my remote would have a 12 hour lapse. If anyone knows why this is that'd be awesome.

static 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';
}

When I return all the details this is what I get on my local server

Server Time: 2016-09-12 02:17:29
2016-09-12 02:04:48 //Posted
12 minutes ago

And when I look at the same thing on my remote server I get

Server Time: 2016-09-12 12:22:37
2016-09-12 12:22:35 //Posted
11 hours ago

This means the times being posted are correct and it's way off on calculating how long it's been.

Morgan Green
  • 1,012
  • 2
  • 10
  • 22
  • You have not the same timezone on your remote server, you should specify the timezone in your `DateTime` objects http://php.net/manual/fr/datetime.settimezone.php or change the timezone of your server – olibiaz Sep 12 '16 at 00:02
  • Are you sure the time on your server is set correctly? – tadman Sep 12 '16 at 00:02
  • When PHP sends it shouldn't it be calculated as the date on the server and local timezone shouldn't matter with a time since while comparing against itself should it? – Morgan Green Sep 12 '16 at 00:03
  • Php used is on the server, so it will be the timezone of the server. – olibiaz Sep 12 '16 at 00:04
  • That's what I thought, so the server sends the timestamp to the mysql server (hosted on the same server) the server itself is set to Los Angeles, It doesn't show what time it was posted, but shows "Time since last posted" – Morgan Green Sep 12 '16 at 00:06
  • 1
    When you create Datetime object try to set UTC timezone. You will be sure that all the datimes are in the same timezone. And before sending it to the client set clients timezone to it. That's all the trick – Andrey Degtyaruk Sep 12 '16 at 03:04
  • UTC did it thank you. – Morgan Green Sep 12 '16 at 04:04

0 Answers0