duanganleng0577 2014-08-07 12:36
浏览 259
已采纳

从客户提供的时间戳(和时区)获取适当的时间

I have a typical php/html/javascript application. There is one main HTML page with a lot of javascript and AJAX calls to PHP to receive/send data.

Among other things, the app tracks certain user actions, recording what the action is and the timestamp of the action. I'm getting the timestamp in javascript as new Date().getTime(). I send the action log to the server, which uses $dt = date('h:i:s', timestamp / 1000) to get a human-digestable time. (Note that for printing purposes I'm only interested in time element, but I need to store the full date/time in the database for later audits.)

My clients can be located anywhere in the world. What I noticed is that when I call date on the timestamp received from the client, the server applies the timezone offset of where the server is located (most likely, the default timezone from php.ini). Thus, if the client in London is passing a timestamp for 10:00:00, the server-printed time ends up being 2:00:00, as the server is in California.

I can easily send the timezone UTC offset with the data (i.e. the value of new Date().getTimezoneOffset()). However I don't quite understand how I should use this timezone offset to get the right printout for the client. It's probably going to be some sort of combination of getting the defualt tz and using the tz from the client - but I just can't get my head around it.

All I want is that the timestamp for 10:00:00 be displayed as 10:00:00 regardless of where the client is or a server is.

  • 写回答

1条回答 默认 最新

  • dplo59755 2014-08-07 12:38
    关注

    Just set the time in the timezone you're working in and then change it to be the user's timezone:

    $date = new DateTime(null, new DateTimeZone('america/los_angeles'));
    $date->setTimeZone(new DateTimeZone('user/timezone')); // user timezone. this one is clearly fake.
    echo $date->format('H:i:s');
    

    You can get the user's timezone from the offset by following this question/answer:

    $offset = -10;
    $tz = timezone_name_from_abbr(null, $offset * 3600, true);
    if($tz === false) $tz = timezone_name_from_abbr(null, $offset * 3600, false);
    echo $tz;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!