Reputation: 11
I'm having an issue with timestamps in my Laravel app. Our database stores timestamps in CEST, but when I cast them to a datetime
object, Laravel automatically converts them to UTC, even though my timezone
is set to CEST
in the config file.
'timezone' => 'Europe/Brussels',
Here's an example of how I'm casting it:
protected $casts = [
'new' => 'datetime'
];
When I don't cast to datetime
, the problem goes away, but for some parts of the app, I need the datetime
format.
I know I can manually convert it like this:
Carbon::parse($new)->setTimezone('CEST')
But I want to avoid doing this conversion manually every time. Is there a way to cast it to datetime
and have it automatically use CEST instead of UTC?
Any help or explanation on why this happens and how to fix it would be greatly appreciated!
Upvotes: 1
Views: 63
Reputation: 11
Store the timestamps in UTC: It's generally a best practice to store all timestamps in UTC and let Laravel handle the timezone conversion automatically based on your app’s configuration. This ensures consistency across different environments and servers.
Manually adjust after casting: If storing in UTC is not an option, you can adjust the timezone after casting like this:
protected $casts = [
'new' => 'datetime:Y-m-d H:i:s',
];
public function getNewAttribute($value)
{
return \Carbon\Carbon::parse($value)->timezone('Europe/Brussels');
}
This will ensure that the new attribute is displayed in CEST.
Use database timezone settings: Ensure your database is set to use UTC (or explicitly convert to UTC on insertion) and rely on Laravel's timezone configuration for output.
Upvotes: 0