使用JavaScript或PHP自动检测用户当前的本地时间 [英] Automatically detect user's current local time with JavaScript or PHP

查看:201
本文介绍了使用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!

问题:基于什么去的秒;用户的OS时钟,主机服务器时间(正负偏移),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 pm(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.

营业时间


这家餐厅现在营业到午夜(AEST)。

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:使用日期()输出用户的计算机时钟时间,这太容易被操纵。

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.

这篇关于使用JavaScript或PHP自动检测用户当前的本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆