Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

calin.ionut's avatar

date cast model with a diff of 3 hours less

In my model I have casted the created_at (laravel 9)

protected casts = [
	'created_at' => 'datetime:d/m/Y H:i'
]

in the table It is saved correctly:

2022-05-31 15:38:33

an in the frontend I get

31/05/2022 12:38

I have set also in the app.php the corect timezone but still ..... a difference of 3 hours less.

Why ?

0 likes
11 replies
calin.ionut's avatar

@Emmanuelpcg

according to the docs:

By default, the date and datetime casts will serialize dates to a UTC ISO-8601 date string (1986-05-28T21:05:54.000000Z), regardless of the timezone specified in your application's timezone configuration option.

so what ever timezone I use in the app.php config it always use UTC.

If using custom format:

If a custom format is applied to the date or datetime cast, such as datetime:Y-m-d H:i:s, the inner timezone of the Carbon instance will be used during date serialization. Typically, this will be the timezone specified in your application's timezone configuration option.

it should use the timezone setting that I provided in the config

Europe/Bucharest
automica's avatar

what do you get in the front end if you return the created_at field without it being defined in $casts array?

CryBaby's avatar

@calin.ionut Did you find out a solution ? I'm facing the same issue right now, the only solution that I got right now is to put the value of create_at in another variable and it will display correctly

$item->created_sat = $item->created_at->format('Y-m-d H:i');

I did this for each item that I got using ->get() on my query.

calin.ionut's avatar

@CryBaby I found a solution to override the default serialization (UTC ISO-8601)

In the model :

protected function serializeDate(DateTimeInterface $date) {
	return $date->format('d/m/Y H:i');
}

but if you have another timestamps or datetime in that table, all will format like that.

2 likes
CryBaby's avatar

@calin.ionut It worked, thank you for your response. but I think they should make if for separate variables in the next versions, maybe we can collaborate to do it since we face the same issue !!

Regards, Rami

Snapey's avatar

it should use the timezone setting that I provided in the config

it depends if the existing times in your database are in local time or in utc

calin.ionut's avatar

@Snapey

it depends if the existing times in your database are in local time or in utc

If I go to mysql and use

select now();

it shows the correct date and time for Europe/Bucharest

Please or to participate in this conversation.