dongqi0644 2013-03-31 15:42
浏览 231
已采纳

如何计算正确的偏移量?

Beginning to learn about the php dateTime & dateTimezone objects. Assuming a server in US/Eastern and creating a time in another timezone, the goal is to convert and store the time (ie London) on the server (US/Eastern), in server time. Using this code:

$runTime = '2013-04-10 07:45:00';
$serverTimezone = new DateTimeZone ( 'US/Eastern');
$checkinTimezone = new DateTimeZone ( 'Europe/London');
$checkinTime = new DateTime ( $runTime, $serverTimezone );

$offset = $serverTimezone -> getOffset ( $checkinTime );

echo "<br/><pre>";
echo 'London: ' . date ( 'Y-m-d H:i', $checkinTime -> format ( 'U' ) ) . "<br/>";
echo "<br/>offset: " . $offset . "<br/>";
echo 'Local: ' . date ( 'Y-m-d H:i', $checkinTime -> format ( 'U' ) + $offset );

-14400 is always returned, wether before or after today (Europe switched to DST earlier today). In an aha moment, I discovered the documentation for getOffset says Returns the timezone offset from GMT.

Is there a simple way to convert that time to US/Eastern? Do I have to go into the getTransitions, find the day DST begins and do the calculation manually? This only matters on the first day of each spring/fall switch.

  • 写回答

1条回答 默认 最新

  • duanbipu7601 2013-04-02 14:21
    关注
    $fromZone = new DateTimeZone('US/Eastern');
    $toZone = new DateTimeZone('UTC'); // assuming the server is going to be UTC going forwards
    
    $dt = new DateTime('2013-04-02 10:00:00', $fromZone);
    $dt->setTimezone($toZone);
    echo $dt->format('Y-m-d H:i:s');
    

    Outputs: 2013-04-02 14:00:00.

    Switch the timezones as needed.


    If you're dealing with just the timestamps, you can simplify things somewhat:

    $fromZone = new DateTimeZone('US/Eastern');
    $dt = new DateTime('2013-04-02 10:00:00', $fromZone);
    echo $dt->getTimestamp();
    

    Outputs: 1364911200

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

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目