DateTime in PHP
Not so long ago, PHP introduced a new DateTime object. This object makes it easier to calculate a date and (re)format it, or make calculations with it. Apart from that, one might say it’s a lot cleaner, code-wise (if you’re an object-oriented type of programmer, like myself).
The object is supported by a second object, DateTimeZone. This object is used for creating a new timezone instance to be used with a DateTime instance.
To fully understand it, here’s an example of starting off with the current timestamp in the UTC (GMT) timezone, and switching the timezone to different ones, with the same timestamp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Create a new DateTime instance, with the current UTC (GMT) timezone. $dt = new DateTime('now', new DateTimeZone('UTC')); echo $dt->format('D F jS Y, H:i:s'); # Outputs: Sun August 15th 2010, 16:21:19 # Switch the timezone to a local timezone. $dt->setTimeZone(new DateTimeZone('Europe/Amsterdam')); echo $dt->format('D F jS Y, H:i:s'); # Outputs: Sun August 15th 2010, 18:21:19 # Switch to a timezone in Australia. $dt->setTimeZone(new DateTimeZone('Australia/Canberra')); echo $dt->format('D F jS Y, H:i:s'); # Outputs: Mon August 16th 2010, 02:21:19 |
Now, imagine a UTC timestamp being saved in a database table and users are able to set their own timezone setting, in order to have all dates and times displayed relative to their own current time. To show you how easy this now is, take a look at the following code:
1 2 3 4 5 6 7 | # We pretend to have two objects, a user and a post. # The user has a timezone setting, the post has a datetime timestamp. $dt = new DateTime($post->date_time, new DateTimeZone($user->date_time_zone)); # That's all there's to it! Now you can display it any way you like. # Maybe in a format also stored in a user's settings: echo $dt->format($user->date_time_format); |
As you can see, wether you want to switch between date and timezones or you just want a generic way to display date and time information, DateTime and DateTimeZone are your object oriented solution.

Leave a reply