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

alfonsogarza's avatar

Casting datetime does not set timezone to UTC

Couldn't find an answer in the myriad of threads on timezones so thought I might ask.

When setting a datetime casted attribute ('date' => 'datetime' in model) from a Carbon instance in another timezone, the timestamp stored is not adjusted to UTC. My config('app.timezone') and postgresql database timezones are both UTC.

    $date = now('America/Monterrey');
    $statistic = Statistic::factory()->create();
    $statistic->update(['date' => $date]);
    dump([
       $date->toString(),  // => "Wed Mar 06 2024 14:55:34 GMT-0600"
        $statistic->date->toString(),  // => "Wed Mar 06 2024 14:55:34 GMT+0000"
        $statistic->date->timezone->getName(),  // => UTC
    ]);

I would have expected $statistic->date to keep the timezone or be 20:55:34 not 14:55:34 because of the -6 hour difference.

My first question is, should it be automatically converted or that something I must handle? To make it work as I expect I must manually set it to UTC before saving: $date->clone()->utc()

If the answer is that Laravel should handle it, what else could be going wrong on my side? Should I be constructing the Carbon instance differently?

PS. This even happens without updating and just setting values $statistic->date = $date;, and with other attribute names that aren't as confusing as date.

Update: I found this thread where it seems like it is not a default behavior, what a bummer. https://github.com/laravel/framework/issues/19737

In this other thread back n 2013, Taylor said I don't think we should magically convert times to a given timezone but the v10 documentation says By default, the date and datetime casts will serialize dates to a UTC ISO-8601 date string (YYYY-MM-DDTHH:MM:SS.uuuuuuZ), regardless of the timezone specified in your application's timezone configuration option.

0 likes
1 reply
alfonsogarza's avatar
alfonsogarza
OP
Best Answer
Level 7

For those wondering what the answer is sadly: Laravel/Eloquent throws away the timezone and you should handle it yourself

Please or to participate in this conversation.