UltraMega Blog

Working With Time Zones in PHP

Let's say you are developing an online application that involves users selecting or viewing times. One problem that you'll need to address is time zones. If your application is going to be used by users all over the world, you'll want to adjust the times to be in their local time zone to prevent confusion. Fortunately, PHP 5.2.0+ greatly simplifies this process with the DateTime and DateTimeZone classes.

The DateTime class provides all the date and time handling functionality, while the DateTimeZone provides DateTime objects with all the time zone information. We just need to provide DateTimeZone with the time zone in the Area/Location format (for example, the time zone in which this server is located is America/Los_Angeles), and it will return an object representing that time zone. We can pass this to a DateTime object to convert any time into this time zone.

Here is an overview of the steps required to accomplish this:

  1. Collect the time zone from the user and store in Area/Location format
  2. Create a DateTimeZone object using the provided time zone
  3. Create a DateTime object, providing it the time in the local time zone
  4. Convert the DateTime object to the time zone created in step 1
  5. Output the time from the DateTime object