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.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by

Recent Premium Tutorials