PHP DateTime class

PHP Dates with Timezone

If you have not already, you will inevitably come across a problem of having to convert dates for user’s timezones. Factor into that daylight savings time and things can get quite messy. As of php 5.2.0, PHP provides a DateTime class to simplify the process of timezones and their offsets.

Let’s see how we get the date using the new DateTime class.

$theDate = new DateTime();

Leaving DateTime() empty will get the current time. Alternatively if you have a date you want to use, provide it as follows.

$theDate = new DateTime(‘2012-02-24 11:25:00’);

This creates a new DateTime object, $theDate.

For this example, we manually set the user timezone as:

$usertz = 'America/Los_Angeles';

By default the DateTime object $theDate uses the timezone from the server.

Now let’s set the timezone for the given object.

$theDate->setTimezone(new DateTimeZone($usertz));

To display the time we can simply use the DateTime format method. This takes on the PHP date() formatting options.

echo $theDate->format('Y-m-d H:i:s')."\n";

So our full example looks like:

$theDate = new DateTime();
$usertz = 'America/Los_Angeles';
$theDate->setTimezone(new DateTimeZone($usertz));
echo $theDate->format('Y-m-d H:i:s')."\n";

Quite simple really. There are much more options and features available than the simple example I have provided. For more information visit the PHP DateTime documentation.