Laravel fix timezone
Posted
•
Updated
Issue
- Laravel save timestamp in database with wrong timezone
- Laravel return resource json with wrong timestamp
Solution
In Laravel version 10
Follow below steps:
1. Replace UTC
by your timezone in config/app.php
Example
app.php
1<?php
2return [
3 /*
4 |--------------------------------------------------------------------------
5 | Application Timezone
6 |--------------------------------------------------------------------------
7 |
8 | Here you may specify the default timezone for your application, which
9 | will be used by the PHP date and date-time functions. We have gone
10 | ahead and set this to a sensible default for you out of the box.
11 |
12 */
13 // Before
14 // 'timezone' => 'UTC',
15 // After
16 'timezone' => 'Asia/Ho_Chi_Minh',
17]
2. Try to refresh your config cache
php artisan config:clear
php artisan config:cache
if you can not delete config cache, try using rm
command remove bootstrap/cache/config.php
, bootstrap/cache/packages.php
, bootstrap/cache/services.php
.
3. Add method to your models which use time, datetime
1<?php
2use DateTimeInterface; // <--- remember add this line
3
4class YourModel extends Model {
5
6 // ---- code ----
7
8 public function serializeDate(DateTimeInterface $date): string
9 {
10 return $date->format('Y-m-d H:i:s'); // <- you can modify this template knckds kncskd kncksd kcsd k kncksd kncsdk ckndsdsc
11 }
12
13}
Now in Resource, you use that method:
1<?php
2
3 public function toArray(Request $request): array
4 {
5 return [
6 // ---- code... ------
7 'createdAt' => $this->serializeDate($this->created_at),
8 'updatedAt' => $this->serializeDate($this->updated_at),
9 ];
10 }