After pulling my hair and abusing Google for a few days I think its time to come to the Laracast Laravel overlords. I'm having an issue with storing and retrieving date time fields. This probably has something to do with the new Laravel 7 date serialislization. Hopefully one of you can point me to the right direction.
The Problem
Let's say I have a User model with an expires_at attribute which is cast to datetime. When fetching a user model the Api will return something like:
{
"id":1,
"name":"Maurine Littel III",
"email":"[email protected]",
"email_verified_at":"2020-01-01T12:00:00.000000Z",
"expires_at":"2020-10-21T20:00:00.000000Z"
"updated_at":"2020-10-22T18:25:29.000000Z",
"created_at":"2020-10-22T18:25:29.000000Z",
}"
If I then post an update request to my api (ie. POST /users/1) with all the values I received from my API, the expires_at attribute suddenly changed -2 hours. The -2 probably comes from the app timezone: Europe/Amsterdam.
But the weird thing is, that the above timestamp which is received and sent is a Z (=UTC) timezone. So if I store the same timezone as I received, it should not change.
The Test
To test what is going wrong I made the simplest failing test I could:
public function testTimezoneIssue() {
$user = User::factory()->create();
$startOfDay = now()->startOfDay();
$user->update(['expires_at' => $startOfDay->toJson()]);
$this->assertEquals($user->expires_at, $startOfDay);
}
Indeed, this test fails:
There was 1 failure:
1) Tests\Feature\ExampleTest::testTimezoneIssue
Failed asserting that two DateTime objects are equal.
--- Expected
+++ Actual
@@ @@
-2020-10-21T22:00:00.000000+0200
+2020-10-22T00:00:00.000000+0200
/Users/michael/Code/timestamp-test/tests/Feature/ExampleTest.php:26
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
But why? Is $startOfDay->toJson() generating a wrong timezone? Or is the datetime mutator messing with the timezone?
Please help me stop pulling my hair. Thanks!