I'm having trouble displaying the correct time. With the UTC default setting in config/app.php, I have a 4 hour difference. When I set the local time zone, I have 2 hours difference. I assume the problem occurs because my database is set to CEST time zone.
mysql> SELECT @@system_time_zone;
+--------------------+
| @@system_time_zone |
+--------------------+
| CEST |
+--------------------+
1 row in set (0.00 sec)
The page I am working on will be used locally, which is why I would like to have the same time in the database as displayed on the page. The time is correctly saved in the database, only the displayed time is changed.
DB -> Laravel
2020-04-21 16:55:08 -> 2020-04-21T14:55:08.000000Z
I wonder if manual modification is a good approach. In this case, I can't change the time zone in the database on the server. Is there any solution or workaround?
UPDATE #1
This solution works correctly if I'm fetch time to blade file.
public function getCreatedAtAttribute($value) {
return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $value, 'Europe/Warsaw');
}
When I get an entry using axios createFromFormat does not accept $value without processing. Unfortunately, this solution does not display the correct time.
public function getCreatedAtAttribute($value) {
$data = \Carbon\Carbon::parse($value);
return $data::createFromFormat('Y-m-d H:i:s', $data, 'Europe/Warsaw');
}
UPDATE #2
I noticed that after setting the local time zone in config/app.php the time is displayed correctly in blade.php files files without any accessors. Unfortunately, when I download entries using axios Laravel returns the wrong time despite the fact that it is saved correctly in the database. The following accessor works fine.
Accessor method:
public function getCreatedAtAttribute($value) {
$data = \Carbon\Carbon::parse($value);
return $data->timezone('Europe/Warsaw');
}
I would like to fetch the time exactly as it is in the database. Otherwise I will have to add accessors to each model.
The easiest and straight forward way to do it is to update each of your model to use Cast in this way by setting $timestamps attribute to false
//Ninja Model
public $timestamps = false;
This means Laravel will not automatically cast created_at and updated_at attributes to a Carbon instance and you can retrieve your values as you get it from the database.
Other than this, if you need to set a system wide timezone for Carbon/Date time generally i.e disregarding what is set by laravel in app.timezone config path. Then you may need to use:date_default_timezone_set('Europe/Warsaw') in the boot() method of your AppServiceProvider class.
Normally, whatever value you set as the timezone value in app config file should be sufficient to enforce app-wide timezone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With