mardi 11 décembre 2018

PHP/Laravel Datetime Automatically Changes

I have a code like below

LocationController

public function updateDriverLocation($id, $lat, $lng)
{
    $location = LocationModel::findOrFail($id);
    $location->lat = $lat;
    $location->lng = $lng;
    $location->last_updated_at = now();
    $location->save();

    TimeHelper::checkArrival($id, $lat, $lng, $location->last_updated_at);

    return $driverLocation;
}

TimeHelper

public static function checkArrival(int $id, $lat, $lng, $lastUpdatedAt)
{
    if (!$lat || !$lng) {
        return false;
    }

    if (strtotime(now()) - strtotime($lastUpdatedAt) > 900) {
        return false;
    }

    $today = date('Y-m-d', strtotime("+ 9 hours"));

    ...
}

When updateDriverLocation is called, now() inside LocationController returns UTC time which aligns with server time, but inside TimeHelper, now() returns localized time. I want to know the reason why it does that. (It applies to php functions like date() and strtotime(), too)

I do have a lot of these like below in Base.php (And Every Model extends it).

public function get`some field name`Attribute($value)
{
     return $this->getLocalizedTime($value); // custom private function
}

As far as I understand, it should not affect the result above, because it should not only affect when data comes from database and this strange behavior even happens to php functions.

I want to know the reason for the behavior described above and also how to prevent that from happening. Any advice or suggestion would be appreciated.

Thank you in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire