简体   繁体   English

PHP DateTime格式不尊重时区?

[英]PHP DateTime Format does not respect timezones?

So I have the following code: 所以我有以下代码:

$timezone = new DateTimeZone('America/New_York');
$datetime = new DateTime(date('r', 1440543600), $timezone);

echo $datetime->format('l, F j, Y - h:i A e');

This outputs the following: 这输出如下:

Tuesday, August 25, 2015 - 11:00 PM +00:00 2015年8月25日星期二 - 晚上11:00 +00:00

You would think it would output: 你会认为它会输出:

Tuesday, August 25, 2015 - 07:00 PM -04:00 2015年8月25日星期二 - 07:00 PM -04:00

How do I get format to output correctly with the set timezone? 如何使用设置的时区正确输出格式?

Read the documentation for DateTime::__construct() , where is says for 2nd parameter: 阅读DateTime::__construct()的文档,其中第二个参数说明:

Note: The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (eg @946684800) or specifies a timezone (eg 2010-01-28T15:00:00+02:00). 注意:当$ time参数是UNIX时间戳(例如@ 946684800)或指定时区(例如2010-01-28T15:00:00 + 02:00)时,将忽略$ timezone参数和当前时区。

Based on that, set timezone on DateTime object after you have created it with unix timestamp: 基于此,在使用unix时间戳创建时,在DateTime对象上设置时区:

$timezone = new DateTimeZone('America/New_York');
$datetime = new DateTime('@1440543600');
$datetime->setTimezone($timezone);

demo 演示

I believe the issue isn't in how you are outputting your date but rather how you are inputting it. 我认为问题不在于您输出日期的方式,而在于您输入日期的方式。 The 'r' format option includes time offset. 'r'格式选项包括时间偏移。

If you create your DateTime object with a string that is devoid of an offset you will get the expected results. 如果使用没有偏移量的字符串创建DateTime对象,则将获得预期结果。

$timezone = new DateTimeZone('America/New_York');
$datetime = new DateTime("2015-08-20 01:24", $timezone);

echo $datetime->format('l, F j, Y - h:i A e');

$datetime->setTimezone(new DateTimeZone('America/Chicago'));
echo "\n";
echo $datetime->format('l, F j, Y - h:i A e');

/* outputs

Thursday, August 20, 2015 - 01:24 AM America/New_York
Thursday, August 20, 2015 - 12:24 AM America/Chicago

*/

See here for an example. 请看这里的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM