Which php date and time tools to use for GMT offsetting
Question
It appears there are many ways to approach date and time massaging in php. I usually am only every dealing with local time. Today, I need to work in UTC.
I am querying against an API, the data they give me about an arbitrary record is: created: Thu, 18 Jun 2009 21:44:49 +0000 * Documented as 'UTC record creation time'
utc_offset: -28800 * Difference between users re
I need to convert that to a simple string to show the user what time and date the data was submitted in their local time.
I believe, the above translates to, if in Calif. for example: Thursday 18th of June 2009 02:44:49 PM
My goal is to get to a time value I can pass to date() for easy formatting in a "pretty" format.
Is it really as simple as converting the above created time to seconds from epoch, adding in the offset, and then passing that to date()? Any gothcha's to look out for?
$created_time = 'Thu, 18 Jun 2009 21:44:49 +0000';
$utc_offset = -28800;
$seconds = strtotime($created_time);
$localized_time = $seconds + $utc_offset;
echo date(DATE_RFC822, $localized_time);
Thanks
Solution
PHP should do thing automatically for you. I can also HIGHLY recommend using the DateTime object instead.
$dt = new DateTime($created_time);
echo $dt->format(DATE_RFC2822);
PHP's date and time functions are timezone aware.. Make sure you're on a recent version of PHP, because a lot of work has been done in improving these systems.
OTHER TIPS
You can use date_default_timezone_set to switch between timezones. In your case, you would pass the timezone information from the user's profile. As Evert recommended, if you are using PHP 5>=5.2, please use the more advanced DateTime class.
<?php
echo date('h:i:s')."\n";
date_default_timezone_set('Europe/Paris');
echo date('h:i:s')."\n";
date_Default_timezone_set('UTC');
echo date('h:i:s')."\n";