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 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决