DhPandya's avatar

Managing various timezones.

Hello all,

In my application Each user is able to select their timezone.

Changing the default timezone dynamically using the config() affecting all the places. Including the database as well.

How we can manage things in a way that database follows the UTC time but at the time of displaying data to user it shows in their local format.

Thanks.

0 likes
2 replies
martinbean's avatar
Level 80

@dhpandya Don’t mess about with the application’s timezone configuration like that.

You should be storing all dates and times as UTC in your database. By all means, let a user specify a preferred timezone in their account settings, but then use that timezone to “present” the UTC values in the user’s preferred timezone.

class User extends Authenticatable
{
    public function formatDateTime(DateTimeInterface $value)
    {
        return Carbon::instance($value)->setTimezone($this->timezone ?? 'UTC');
    }
}

You can then use that method on the User model to present date and time values in the user’s preferred timeone:

<p>Foo created at {{ $user->formatDateTime($foo->created_at)->toDateTimeString() }}.</p>
1 like

Please or to participate in this conversation.