How to set local timezone in laravel

15,909

Don't do that. Never set the global Laravel timezone to user's timezone. You'll face endless problems.

Choose you application timezone, set the Laravel config to that timezone and never change it.

Instead, when you need to show a date in user's timezone do something like

User::find(1)->foobazed_at->timezone(Auth::user()->timezone);

To control which model columns are automatically converted to Carbon\Carbon instances, add the following method to your model file:

public function getDates()
{
    return array('foobazed_at', static::CREATED_AT, static::UPDATED_AT, static::DELETED_AT);
}
Share:
15,909

Related videos on Youtube

Roy M J
Author by

Roy M J

strong textI speak JS

Updated on June 22, 2022

Comments

  • Roy M J
    Roy M J almost 2 years

    Is there a way to set local timezone in laravel?

    In config/app.php

    'timezone' => 'UTC',
    
    • What should be added so that timezone value above uses local timezone?

    After some research, stumbled upon the following PHP way of dealing with it:

    $userTimezone = Auth::user()->timezone;
    
    date_default_timezone_set($userTimezone);
    
    // and change the configuration so they match
    
    Config::set('app.timezone', $userTimezone)
    

    But, Is there an elegant solution for this other than converting the timezone using the above code.

    Cheers

  • Roy M J
    Roy M J almost 9 years
    Make sense...What your suggesting is to keep the timezone UTC itself and alter it while displaying only. ? While beautifying date format to say "a few min ago", will this ever say "10 min from now". We're dealing with created_at/updated_at default values in db.
  • Javi Stolz
    Javi Stolz almost 9 years
    Yes, keep the App timezone fixed. Make conversion when you dislay, not when you store. UTC is a great choice since it's universal and has no daylight savings. To show human friendly relative dates you can use ->foobazed_at->timezone($timezone)->diffForHumans()
  • George G
    George G almost 7 years
    what about when you need to do some queries with dates in db? for example u stored UTC date, but now user from new york, and you want to see if he already has some entries in the db for today?
  • Javi Stolz
    Javi Stolz over 6 years
    Then you need to do the convert the dates to the desired timezone. You can do it either before the query with Carbon (which is included with Laravel) either on the fly using DB functions (for instance Mysql's CONVERT_TZ function)