Laravel how to simply display datetime on browser in different user locations

Hoang Viet Nguyen
kiss-everything
Published in
2 min readSep 29, 2020

--

Summary

  1. Add new column “timezone”
  2. Save user’s timezone to database
  3. Show datetime on web with saved timezones

Details

Step 1
In table “users”, add new column named “timezone”, with type varchar to store user’s timezone:
- You can create migration file then do migrate (https://laravel.com/docs/7.x/migrations#generating-migrations)
- Or simply run this sql command:

alter table users add column timezone varchar(191);

Step 2
Way 1: Automatically update timezones when user login

In App\Http\Controllers\Auth\LoginController, override authenticated function:

protected function authenticated(Request $request, $user)
{
… //other code here
$ipInfo = Http::get(‘http://ip-api.com/json/' . $request->ip());
$timezone = $ipInfo->json()[‘timezone’] ?? ‘Asia/Bangkok’;
$user->update([‘timezone’ => $timezone]);
}

In above snippet, we used Laravel Http Client and a third party service (https://ip-api.com/) to get user’s timezone from his IP address, then save it to database.

There are many other free or commercial third party services to choose from. Search and find one that suit your needs.

Note: To save response time of login requests, you can create new Laravel job and do necessary task there

Way 2: Let user select their timezones
In register form, add select timezone input besides email, name, password, etc… then modify the register controller and user model if needed to store timezone once user hit register button

Step 3
In blade files, call setTimezone method to display datetime in user’s timezone
Example:

{{$post->updated_at->setTimezone(auth()->user()->timezone)
->format('Y-m-d H:i')}}

Good luck!

--

--