views:

409

answers:

2

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

+2  A: 
Evert
Thanks. The DateTime object manual is pretty deep, I will review. What I am still after though, is how to correctly deal with the offset.I am given, from the docs, what is supposed to be a UTC value for $created_time. The only other date/time value I am given is an offset. Users data comes from all over the world, the offset will be different depending on what zone they are in.I assume I just shift the object to seconds, add in the offset, and convert that to a pretty string?
The idea is with both DateTime and strtotime, if you specify the timezone in a standard format, it will pick it up and automatically convert to your own specified timezone.The other way round (see the second commenter) is by changing the default timezone temporarily, or give the DateTime object a DateTimeZone object
Evert
A: 

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";
Shoan
Thanks. I only get an offset, the timezone data I get is not formatted in a way of php's "List of Supported Timezones". I would rather not massage that data, and then risk it changing.What do you think about taking the offset, and mapping that to each of the values "date_default_timezone_set()" accepts? Or, is there perhaps a function I am missing that already does that?
If you have the offset, just convert it to hours and use one of the timezones here: http://us2.php.net/manual/en/timezones.others.php . In your example $utc_offset = -28800; would be (-28800 / 3600) = -8 so 'Etc/GMT-8' is what you want.
Mike B