How to Format Date with Time Zone using Carbon – Laravel

Managing multiple time zones in a date and time related application can be difficult. Especially when dealing with time zones that have huge time differences. For example, Australia and the USA are completely opposite on the globe and have substantial time differences. When working on such applications using Laravel, the PHP API Carbon serves as a great solution. It helps format date with time zone based on the user’s current time zone. Let us go through the process the package makes this possible.

Format Date with Time Zone using Carbon

You can set a default time zone for your application in you app.php file that comes under the config directory of you Laravel application. The default time zone is set to UTC. However, you can change it anytime.

Next, you need to get the user’s current time zone. As you application might be used by people in USA, Asia, or Australia. Each location should show up the right time.

To simply find the current user time zone, you may save it in a session when a user gets authenticated as shown below.

 protected function authenticated(Request $request, $user)
    {
        session(['timezone' => $request->timezone]); // saving to session
    }

Now to format date with time zone, you will pass the session variable (time zone) to Carbon, as shown below.

Carbon::parse($date)->timezone(session('timezone'))

In case you already have a (hard coded) time zone available. You can use it in Carbon to format dates as follows.

$timestamp = '2014-02-06 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Europe/Stockholm');
$date->setTimezone('UTC');

Hope you understand how simply the Carbon API can format dates and help in multi time zone applications to format dates and time as per the user’s current time zone.

Leave a Comment