Laravel timestampTz columns have the wrong timezone

Viewed 525

I'm using Postgres 13 with Laravel 8.4.4

Setting the Unix timestamp 1607207809 for an Eloquent model property which is defined as cast to datetime, we get the correct Carbon time, 2020-12-05 22:36:49.0 +00:00.

However, saving this model instance, where that column is defined in the migration as a timestampTz column, results in 2020-12-05 22:36:49-08 being saved. This is not the correct timezone, resulting in an incorrect time.

In config/app.php, the timezone is set to UTC. My computer's timezone is Pacific Time, so it would appear that is taking precedence somehow. Any ideas why?

I would have expected the timestamp to be saved using the timezone encoded in Carbon, but apparently not?

2 Answers

The best solution I've found is to define $dateFormat = 'Y-m-d H:i:s P' on the model while casting to datetime.

A custom Cast class (https://laravel.com/docs/8.x/eloquent-mutators#custom-casts) should not be used because when creating a new object, the created_at and updated_at properties are not yet set.

Without defining $dateFormat, the $value parameter passed to the Cast class setter for created_at and updated_at is in the format 'Y-m-d H:i:s'.

This is not a problem if your database server(s) are set to the same timezone as your app, but mistakes happen.

You can set the timezone use by the entire laravel aplication by using date_default_timezone_set function to set timezone.

In the AppServiceProvier add this code

public function boot(){
     date_default_timezone_set('Pacific/xxxxxx');
}

Check the name of your timezone here Pacific Zone.

Related