Format PHP DateTime in Specific Timezone

This article explains how to format a PHP DateTime object to display the date and time in a specific timezone. You will learn how to initialize a date, apply the DateTimeZone class to change its timezone, and format the final output for the user.

To display a date and time in a specific timezone in PHP, you must combine the built-in DateTime and DateTimeZone classes. The process involves instantiating a date, setting its timezone to your target region, and then formatting the output.

Here is a direct example of how to convert and format the current time to a specific timezone:

<?php
// 1. Create a DateTime object (defaults to the server's timezone)
$date = new DateTime('now');

// 2. Define the target timezone
$targetTimezone = new DateTimeZone('America/New_York');

// 3. Set the timezone on the DateTime object
$date->setTimezone($targetTimezone);

// 4. Format and display the time
echo $date->format('Y-m-d H:i:s T'); 
// Output example: 2023-10-27 10:30:00 EDT

Key Components Explained

Example: Converting UTC to a Local Timezone

Storing dates in UTC (Coordinated Universal Time) within your database is a development best practice. When displaying these times to users, you can convert them to their local timezone:

<?php
// Create a DateTime object representing a stored UTC time
$utcDate = new DateTime('2023-10-27 14:00:00', new DateTimeZone('UTC'));

// Convert the UTC time to the Paris timezone
$utcDate->setTimezone(new DateTimeZone('Europe/Paris'));

// Output the formatted local time
echo $utcDate->format('g:i A T'); 
// Output: 4:00 PM CEST