开发者

PHP to output a local timezone adjusted DateTime

I was u开发者_StackOverflow中文版nder the impression that the format() function of the PHP DateTime class exported the timestamp it was initially passed with the correct offset applied to it.

I've come to realise that it doesn't make sense for it to do that. I therefore want to store the timestamp from the database (UTC) in the object along with the user's timezone, and be able to output it according to whether I want a UTC date or a user timezone adjusted date.

I've begun extending the DateTime class to do this but I'm wondering if I'm missing something in either the existing methods in DateTime or the thought process behind why the DateTime class works the way it does.

Presumably I'll also need a couple of static factory methods which can take a timestamp, timezone and whether the timestamp passed in is a user adjusted timestamp or a UTC timestamp, and be able to make the necessary adjustments to instantiate a standardised DateTime object from the UTC version of the time passed in. In this way I'd be able to throw timestamps around the UI and database and be able to convert between them appropriately.

Is there a simpler way? I've seen the date_default_timezone_set function but I want to avoid having that setting affect the whole script, leading to user adjusted times being stored in the DB.

(I'm storing users' timezones in the DB as the timezone string, such as Europe/Berlin, to pass into the functions from a user session variable. I also intend to store all datetimes as UTC times and leave the server's php.ini set to UTC as well.)


You can create the DateTime instance, specifying that it is UTC. Then change its timezone to that of the user with setTimeZone().

$datetime = new DateTime("2011-06-07 12:34:56", new DateTimeZone("UTC"));
$datetime->setTimeZone(new DateTimeZone("Europe/Berlin"));
echo $datetime->format(DateTime::RSS);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜