Time Zone in the View Layer

372 views Asked by At

I'm writing my application with 'UTC' as the time zone. I have a timezone column for each user. I am going to use this value in the presentation layer. Date/time outputs and inputs will be using it.

I will also be presenting dates and times in the view layer when there's no current user. I want the fallback time zone to be the application one. I want to avoid putting logic like this every time:

$now = new Carbon();
if (!Auth::guest()) {
    $now->setTimezone(Auth::user()->timezone);
}

All this finally leads me to my question. Where/how is a good place to set the view layer time zone?

I'm providing my own answer, but I'm looking for better solutions, criticisms, etc.

1

There are 1 answers

0
Sonny On

Set the session value during authentication (login)...

Auth::login($user);
session(['timezone', $user->timezone]);

Use it in the view layer...

{{ \Carbon\Carbon::now()->setTimezone(session('timezone'))->format('h:i A T') }}