dsovc00684 2014-02-11 14:48
浏览 52
已采纳

尝试使用dateTime类以GMT,PST和EST显示当前时间

I have attempted to do this using the following code:

$date = new DateTime('now');

$datePST = $date->setTimezone(new DateTimezone('PST'));

$dateEST = $date->setTimezone(new DateTimezone('EST'));

echo $date->format('H:i:s');
echo '<br />';
echo $EST = $dateEST->format('H:i:s');
echo '<br />';
echo $PST = $datePST->format('H:i:s');

But they all output the same time. Why are they not outputting the correct times?

  • 写回答

1条回答 默认 最新

  • douluan4644 2014-02-11 14:50
    关注

    Because they are all pointing to the same object. So when you change the timezone in one you are changing it for all of them.

    $date = new DateTime('now');
    echo $date->format('H:i:s');
    echo '<br />';
    $date->setTimezone(new DateTimezone('PST'));
    echo $date->format('H:i:s');
    echo '<br />';
    $date->setTimezone(new DateTimezone('EST'));
    echo $date->format('H:i:s');
    

    If you want to have separate variables for each timezone you can use clone to create new objects:

    $date = new DateTime('now');
    $datePST = clone $date;
    $datePST = $datePST->setTimezone(new DateTimezone('PST'));
    $dateEST = clone $date;
    $dateEST = $dateEST->setTimezone(new DateTimezone('EST'));
    
    echo $date->format('H:i:s');
    echo '<br />';
    echo $EST = $dateEST->format('H:i:s');
    echo '<br />';
    echo $PST = $datePST->format('H:i:s');
    

    If you're using PHP 5.5 you can use the new DateTimeImmutatable() class as well:

    $date = new DateTimeImmutable('now');
    $datePST = $date->setTimezone(new DateTimezone('PST'));
    $dateEST = $date->setTimezone(new DateTimezone('EST'));
    

    FYI, using "now" is unnecessary as when no parameter is passed to DateTime() it automatically defaults to the current date and time..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改