W3docs

Format Timezone for Carbon Date

To format a timezone for a Carbon date in PHP, you can use the format() method and include the e or I format codes.

To format a timezone for a Carbon date in PHP, you can use the format() method and include the e or I format codes. For example:

Example: Using the format() method

$date = Carbon::now();
$formattedDate = $date->format('Y-m-d H:i:s e');

The e format code will output the full timezone identifier (e.g., Europe/Paris, America/New_York). The I format code indicates whether daylight saving time is in effect (1 for yes, 0 for no). To output the timezone offset in hours and minutes from UTC, use P or O instead (e.g., +07:00).

Alternatively, you can use the setTimezone() method to set the timezone before formatting the date. Note that Carbon v2 and v3 use immutable instances, so setTimezone() returns a new instance instead of modifying the original.

Example: Using the setTimezone() method

$date = Carbon::now();
$date = $date->setTimezone('Europe/Paris');
$formattedDate = $date->format('Y-m-d H:i:s e');

You can also pass a DateTimeZone object to setTimezone() instead of a string:

Example: Passing a DateTimeZone object

$date = Carbon::now();
$date = $date->setTimezone(new DateTimeZone('Europe/Paris'));
$formattedDate = $date->format('Y-m-d H:i:s e');

The timezone passed to the above methods can be any valid timezone identifier. This method is available in both Carbon v2 and v3.