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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题