问题描述
对于我们这些使用标准共享托管包(例如 GoDaddy 或 Network Solutions)的人,当您的托管服务器 (PHP) 和 MySQL 服务器位于不同时区时,您如何处理日期时间转换?
For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones?
另外,对于确定您网站的访问者所在的时区和适当地操作日期时间变量,是否有人提供了一些最佳实践建议?
Also, does anybody have some best practice advice for determining what time zone a visitor to your site is in and manipulating a datetime variable appropriately?
推荐答案
从 PHP 5.1.0 开始,您可以使用 date_default_timezone_set() 函数设置脚本中所有日期/时间函数使用的默认时区.
As of PHP 5.1.0 you can use date_default_timezone_set() function to set the default timezone used by all date/time functions in a script.
对于 MySql(引自 MySQL 服务器时区支持 页)
For MySql (quoted from MySQL Server Time Zone Support page)
在 MySQL 4.1.3 之前,服务器只在启动时设置的系统时区运行.从 MySQL 4.1.3 开始,服务器维护了几个时区设置,其中一些可以在运行时修改.
Before MySQL 4.1.3, the server operates only in the system time zone set at startup. Beginning with MySQL 4.1.3, the server maintains several time zone settings, some of which can be modified at runtime.
您感兴趣的是时区的每个连接设置,您将在脚本开头使用它
Of interest to you is per-connection setting of the time zones, which you would use at the beginning of your scripts
SET timezone = 'Europe/London';
至于检测客户端时区设置,您可以使用一些 JavaScript 来获取该信息并将其保存到 cookie,并在后续页面读取时使用它来计算正确的时区.
As for detecting the client timezone setting, you could use a bit of JavaScript to get and save that information to a cookie, and use it on subsequent page reads, to calculate the proper timezone.
//Returns the offset (time difference) between Greenwich Mean Time (GMT)
//and local time of Date object, in minutes.
var offset = new Date().getTimezoneOffset();
document.cookie = 'timezoneOffset=' + escape(offset);
或者您可以让用户自行设置时区.
Or you could offer users the chioce to set their time zones themselves.
这篇关于处理不同时区的PHP服务器和MySQL服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!