Timezone settings for created_at and similar fields

If you install a fresh Laravel and create your app, you may notice that all created_at and other timestamp fields in database are being saved in UTC timezone. How to change it? Easy.

We go to the file config/app.php and look for this entry:

    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone'        => 'UTC',

As you can see, UTC is a default value for Laravel. So you can easily change it here to, for example, Europe/London or America/Los_Angeles – see full list of PHP-supported timezones here.

If you change this settings, unfortunately old entries won’t be changed automatically, but new ones will be saved with created_at, updated_at and similar fields in your specified timezone.

Another thing to consider – if you have an international project, it does make sense to save time in UTC. Strategy is quite simple – store all timestamps in UTC, and if you need it to be shown in specific case with a different timezone (for example, for a user who lives in different country), you convert it to that particular timezone on-thy-fly with Carbon library, which is inside of Laravel already – you don’t need to add or install any packages.
Like this:

$user->created_at->timezone('Europe/London')->format('H:i');

In general, I recommend using Carbon for dealing with date/time whenever possible, it’s an awesome library – you just have to read the docs and get used to using it properly.

Like our articles?
Check out our Laravel online courses!

4 COMMENTS

  1. Is it better to always have UTC format and then show the date by user timezone with Carbon?
    I think It gives more flexibility now and in the future, when your project could extend?

  2. Yaroslav is right. You shouldn’t do all this extra configuring and using the Carbon class.
    Mysql timestamps are held in UTC by default and they should stay that way. You only have to set the timezone on your mysql client to convert to your local timezone.

LEAVE A REPLY

Please enter your comment!
Please enter your name here