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 关于网上一个easyx制作的见缝插针小游戏(c++)
    • ¥15 开地址法双散列函数处理碰撞
    • ¥15 想问一下这个是什么情况 虚拟机Linux打不开了
    • ¥15 联通光猫掉注册了怎么重新注册上去
    • ¥15 关于unity开发steamvr程序遇到的问题
    • ¥60 求tc downloader的下载方式
    • ¥15 华为 快捷方式 手电筒 接口
    • ¥15 Qt6.5支不支持Android13开发啊
    • ¥20 网络只能跑一半,应该如何设置
    • ¥20 Python调用百度开发者平台人脸识别接口