dongtiao6362 2015-08-20 05:06
浏览 125
已采纳

PHP DateTime格式不尊重时区?

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

You would think it would output:

Tuesday, August 25, 2015 - 07:00 PM -04:00

How do I get format to output correctly with the set timezone?

  • 写回答

2条回答 默认 最新

  • dphfwzn8269 2015-08-20 06:42
    关注

    Read the documentation for DateTime::__construct(), where is says for 2nd parameter:

    Note: 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).

    Based on that, set timezone on DateTime object after you have created it with unix timestamp:

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

    <kbd>demo</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • doujia2463 2015-08-20 05:24
    关注

    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.

    If you create your DateTime object with a string that is devoid of an offset you will get the expected results.

    $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 "
    ";
    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.

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#c++#的问题:c++如何使用websocketpp实现websocket接口调用,求示例代码和相关资料
  • ¥15 51单片机的外部中断,按下按键后不能切换到另一个模式
  • ¥15 java连接sqlserver有问题
  • ¥15 yolov8 如何调cfg参数
  • ¥15 这个四人抢答器代码哪儿有问题?仿真程序怎么写?
  • ¥15 burpsuite密码爆破
  • ¥15 关于#ubuntu#的问题,如何解决?(相关搜索:移动硬盘)
  • ¥15 scikit安装之后import不了
  • ¥15 Ros2编译一个使用opencv的c++节点的时候,报了这个错误,请问怎么解决啊
  • ¥15 人脸识别相关算法 YOLO,AI等