daninthemix's avatar

Setting DB_TIMEZONE at runtime

I was having that irritating issue where Lumen was writing all DB timestamps 1 hour behind, because I'm on BST (Daylight Savings Time) at the moment. And yes - the timezone is configured as 'Europe/London'.

I can fix it by adding DB_TIMEZONE=+01:00 to .env, but that's not really a fix, is it? Because the other half of the year I need it set to +00.00.

This was going to be a question but instead it's become a solution - what I did (and has worked) is copy the example database config file from the Lumen source into app\config, load it in bootstrap\app.php, and replace this line under the MySQL section:

'timezone' => env('DB_TIMEZONE', (date('I') === '1') ? '+01:00' : '+00:00')

0 likes
3 replies
Cronix's avatar

I totally agree with the above. Store everything in UTC, and let the users set their timezone. I just store their timezone on the user table.

Then when outputting dates, just use carbon to convert the date to their timezone for display. {{ $model->dateField->setTimezone($user->timezone) }}

When the user submits something with a date, create the date with their timezone, and convert it back to utc to store it. $date = Carbon::parse($userSuppliedDateTime, $user->timezone)->setTimezone('utc');

If you do that, you will never have a problem. Users will always see the correct date/time for their local timezone, which adjusts for DST automatically, and all of your datetimes will be stored in UTC for consistency.

Please or to participate in this conversation.