Building off my last post, where I showed you how to easily display any public Twitter feed on your site, I ran into another problem: the dates that are delivered by the Twitter API all reflect Greenwich Mean Time (GMT). Now I thought about going the old route and doing some convoluted math using date(), strtotime(), and mktime(), but I thought it was time find a serious solution, one that would allow me to display the correct time for whatever timezone I wished.

So while searching the web, I came across an insightful post that discussed PHP’s built-in DateTime object. I try hard to keep up with all the tech in my job, but this one got through the cracks, and I was instantly intrigued. So after some research and fiddling, I came up with the following block of code, which will allow you to easily translate dates/times to and from any timezone.

The process is a little convoluted, so here’s what’s going on. First we must set the system-wide timezone to match that of the date/time we would like to translate. In this example, it’s about 4:50pm on Nov 25, 2008 in the GMT timezone. Next we create a DateTime object with that time (FYI you can use any format accepted by strtotime()).

Next we create a DateTimeZone object. Keep in mind that this step stands completely on its own, and can be performed anytime up to now.

Finally, we pass the DateTimeZone object as the lone argument in a call to the setTimezone() method. This will change the timezone stored in $datetime from GMT to EST, and automatically update the date/time accordingly, which we output with a call to the format method.

Note that I used object-oriented syntax for this process, but there is a procedural style (i.e. functions) as well. I prefer OOP here because it’s just easier to read and follow.

Sidenote: While I was working on this I found GMT and UTC used almost interchangeably. For all intents and purposes, they are identical. But there is a technical difference: GMT is based on the rotation of the earth (less precise), while UTC is based on an atomic clock (more precise). Don’t worry, you and I are not the only ones who got confused.

Nice job! The ability to “function-ize” a given code snippet is always a clear sign that someone has grasped the concept(s) at work. This is precisely why I usually don’t provide functions, opting instead for blocks of code that people can read, understand, and then apply.