I'm working on a new Laravel 7.1 app (Not an upgrade) But it seems that working with dates serialization loose the timezone.
config/app.php
'timezone' => 'Europe/Zurich',
tinker example
>>> \Carbon\Carbon::parse('2020-06-22')->timezone
=> Carbon\CarbonTimeZone {#3251
timezone: Europe/Zurich (+01:00),
}
>>> \Carbon\Carbon::parse('2020-06-22')->toJson()
=> "2020-06-21T22:00:00.000000Z"
So, when I parse the date back, I'm not getting the proper date.
>>> new \Carbon\Carbon('2020-06-21T22:00:00.000000Z')
=> Carbon\Carbon @1592776800 {#3266
date: 2020-06-21 22:00:00.0 +00:00,
timezone: "Z",
}
>>> (new \Carbon\Carbon('2020-06-21T22:00:00.000000Z'))->format('Y-m-d')
=> "2020-06-21"
Currently I'm doing it like this
$date = Carbon::parse('2020-06-21T22:00:00.000000Z')
->setTimezone(config('app.timezone'));
As alternative I can change the default date format in my models, as stated in the doc
/**
* Prepare a date for array / JSON serialization.
*
* @param \DateTimeInterface $date
* @return string
*/
protected function serializeDate(DateTimeInterface $date)
{
return $date->toIso8601String(); // 2019-02-01T03:45:27+00:00
}
But it would be preferable that Carbon::parse()
and/or new Carbon()
take my timezone by default, I guess.-