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..

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

报告相同问题?