Converting PHP Date string to UTC

Oct 19, 2010   #datetime  #php  #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.

  1. Convert the string to a DateTime object.
  2. Pass a DateTimeZone object for the new timezone (in my case “UTC”) to your DateTime object.
  3. Now your DateTime object is in the new timezone.

So simple! Check out this sample script and enjoy!

<?php
$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