Converting PHP Date string to UTC
We store all of our dates in the database in UTC. This makes it easy for us to pass dates around to our various applications (web, iPhone, iPad) and all pieces know how to convert to their respective local time. I came across an issue this afternoon that I had not encountered previously, since most of the dates that we store are generated on the server side either using gmdate() in PHP or UTC_TIMESTAMP() in MySQL. This particular issue arose from the iPhone app reporting a date to us. This date was sent in the following format: Y-m-d H:i:s O (i.e. ‘2010-10-10 10:10:00 -0600’). I had a hard time getting this string converted to UTC, so I figured I would post an example for future reference. It’s embarrassing how easy it was. First, convert the string to a DateTime object. Then pass a DateTimeZone object for the new timezone (in my case “GMT”) to your DateTime object. Now your DateTime object is in the new timezone. So simple! Check out this sample script and enjoy!
$d = new \DateTime('2010-10-10 10:10:00 -0600'); echo 'The date is ' . $d->format('Y-m-d H:i:s O') . '<br />'; //The date is 2010-10-10 10:10:00 -0600 $d->setTimezone(new \DateTimeZone('GMT')); echo 'The new date is ' . $d->format('Y-m-d H:i:s O'); //The new date is 2010-10-10 16:10:10 +0000