是否有一种标准的方法可以让服务器在网页中确定用户的时区?
可能来自HTTP报头或用户代理字符串的一部分?
是否有一种标准的方法可以让服务器在网页中确定用户的时区?
可能来自HTTP报头或用户代理字符串的一部分?
当前回答
一个可能的选项是使用Date报头字段,该字段在RFC 7231中定义,应该包括时区。当然,不能保证该值真的是客户机的时区,但它可以作为一个方便的起点。
其他回答
下面是一篇文章(带源代码),解释如何在ASP中确定和使用本地化时间。净(VB。NET, c#)应用程序:
是时候了
In short, the described approach relies on the JavaScript getTimezoneOffset function, which returns the value that is saved in the session cookie and used by code-behind to adjust time values between GMT and local time. The nice thing is that the user does not need to specify the time zone (the code does it automatically). There is more involved (this is why I link to the article), but provided code makes it really easy to use. I suspect that you can convert the logic to PHP and other languages (as long as you understand ASP.NET).
到目前为止,还没有报告客户端时区的HTTP标头,尽管有人建议将其包含在HTTP规范中。
如果是我,我可能会尝试使用客户端JavaScript获取时区,然后使用Ajax或其他工具将其提交给服务器。
它是简单的JavaScript和PHP:
即使用户可以打乱他/她的内部时钟和/或时区,我迄今为止发现的最好的方法,以获得偏移量,仍然是新的Date(). gettimezoneoffset();。它是非侵入性的,不会让人头痛,也不需要依赖第三方。
假设我有一个表,users,其中包含一个字段date_created int(13),用于存储Unix时间戳;
假设客户端创建了一个新帐户,数据是通过post接收的,我需要用客户端的Unix时间戳插入/更新date_created列,而不是服务器的。
由于在插入/更新时需要timezoneOffset,因此当客户端提交表单时,它作为额外的$_POST元素传递,从而消除了将其存储在会话和/或cookie中的需要,并且也没有额外的服务器访问。
var off = (-new Date().getTimezoneOffset()/60).toString();//note the '-' in front which makes it return positive for negative offsets and negative for positive offsets
var tzo = off == '0' ? 'GMT' : off.indexOf('-') > -1 ? 'GMT'+off : 'GMT+'+off;
假设服务器接收到tzo为$_POST['tzo'];
$ts = new DateTime('now', new DateTimeZone($_POST['tzo']);
$user_time = $ts->format("F j, Y, g:i a");//will return the users current time in readable format, regardless of whether date_default_timezone() is set or not.
$user_timestamp = strtotime($user_time);
插入/更新date_created = $ user_timestamp。
当检索date_created时,你可以像这样转换时间戳:
$date_created = // Get from the database
$created = date("F j, Y, g:i a",$date_created); // Return it to the user or whatever
现在,这个示例可能适合您的需要,当涉及插入第一个时间戳时……当涉及到额外的时间戳或表时,您可能需要考虑将tzo值插入到用户表中以供将来参考,或者将其设置为会话或cookie。
P.S.但是如果用户旅行并切换时区怎么办?在GMT+4登录,快速移动到GMT-1,然后再次登录。最后一次登录将在将来。
我认为……我们想得太多了。
你可以在客户端使用moment-timezone将值发送给服务器;示例用法:
> moment.tz.guess()
"America/Asuncion"
使用jQuery在AJAX请求上提交时区偏移量作为HTTP报头
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-TZ-Offset", -new Date().getTimezoneOffset()/60);
}
});
您还可以通过使用moment.tz.guess();从http://momentjs.com/timezone/docs/ # / using-timezones / guessing-user-timezone /