使用 JavaScript 或 PHP 自动检测用户当前的本地时间
我经常需要根据不同时区的用户实际当地时间显示信息或受其影响.是否有可靠的方法来获取用户的当前时间和/或时区?
I often need to display information based on or influenced by a user's actual local time which differs across time zones. Is there a reliable way of getting a user's current time and/or timezone?
关键问题:
- 服务器端代码基于网站主机或用户的 ISP
- 客户端代码基于用户的系统时钟,太容易操纵了
关键问题:
- 是否需要精确定位用户的地理位置?
- ISP 时间可以作为准确的指南吗?
- 用户操作系统时钟可以变化或由用户修改?
例子:
倒计时:
仅剩 1 小时 3 分 56 秒!
Only 1 hour, 3 minutes, 56 seconds to go!
问题:秒走基于什么;用户的操作系统时钟、主机服务器时间(正负偏移)、ISP 系统时间.如果所有时区的时钟同时结束,这很容易,但如果它是用户本地时区午夜的倒计时,则更棘手)
Issue: seconds to go based on what; The user's OS clock, the hosts server time (plus or minus offset), ISP system time. This is easy if the clock finishes at the same time for all timezones, but trickier if it's a countdown to something like midnight in the user's local time zone)
编辑日志
项目于下午 3:03(10 秒前)发布
Item posted at 3:03pm (10 seconds ago)
问题:10 秒"的计算与用户无关,调整时间以匹配用户的时区.
Issue: "10 seconds" is calculated regardless of user, the time is adjusted to match the user's time zone.
开放时间:
这家餐厅现在营业至午夜(澳大利亚东部标准时间).
This restaurant is open now until midnight (AEST).
问题:可以通过从服务器端偏移来计算像午夜这样的时间,但使用像现在这样的 psudo 时间,2 小时内是基于用户的时间.
Issue: Giving a time such as midnight can be calculated by offsetting from the server-side but using psudo times such as now, in 2 hours is based on the user's time.
PHP: 使用 time()
输出服务器时间.这可以根据用户的时区进行偏移.
PHP: using time()
outputs the server time. This can be offset depending on the user's timezone.
JavaScript: 使用 Date()
输出用户的计算机时钟时间,太容易操纵了.
JavaScript: using Date()
outputs the user's computer clock time which is too easily manipulated.
推荐答案
总之没有.
我建议使用服务器端时间,并让用户能够选择他们的时区.
I would suggest using server side time, and have the ability for the user to choose their time zone.
您可以根据用户 IP 地址的启发式方法计算用户的默认时区,但这很容易出错.
You could possibly calculate default time zones for users based on heuristics around their IP address, but this is open to error.
您应该能够通过 javascript/Ajax 提取客户端时区信息,但与时间本身一样,这也容易出错.
You should be able to extract client side time zone information through javascript / Ajax, but as with the time itself this is also open to error.
我的建议:让用户根据您期望用户所在的位置选择具有合理默认值的时区.
My recommendation: Let users choose their time zone with a sensible default based on where you expect your users to be.
相关文章