开发者

PHP DateTime Inconsistency? What am I missing?

Using PHP 5.2.5 I was working with some DateTime objects and noticed a time that seemed off. The problem I'm having may be related to timezones, but I'm not sure - I'm creating a DateTime from a Unix Time Stamp and getting different/unexpected results depending on how I output it.

I created the following to easily illustrate the "issue":

$timezone = new DateTimeZone('America/Chicago'); 
$now = time(); 
$now_datetime = new DateTime('@' . $now, $timezone); 
echo phpversion() . "\n\n"; 
echo $now . "\n"; 
echo $now_datetime->format('U') . "\n\n"; 
echo date('g:i:sa', $now) . "\n";
echo $now_datetime->format('g:i:sa') . "\n\n";

This outputs the following:

5.2.5

1287676530
1287676530

10:55:30am
3:55:30pm

I'm currently in the correct timezone, and the server shows the "right" time (10am) when using the date() function to output a formatted date, as well as 'America/Chicago' being the default timezone on that machine. But, when outputting values via DateTime::format(), the times are very different.

I added the ->format('U') just to verify that it was holding the correct timestamp.

So,开发者_如何学编程 I'm probably doing something wrong or I have the wrong expectations. So what am I missing?

It seems like a timezone issue with DateTime, but if that's the case, why does it show "now" in America/Chicago as ... wrong?


The timezone you 'insert' into DateTime is the timezone of the string, which may not be your current timezone, so PHP can calculate the actual datetime, not the timezone it uses to format your output. If you want it to output the time in a specific timezone, use $now_datetime->setTimezone($timezone).


The manual on DateTime's constructor has the answer:

The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

This means that your timestamp is treated as a GMT one, explaining the 7 hours' difference.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜