【发布时间】:2025-11-22 09:35:01
【问题描述】:
我在我的服务器上的所有日期/时间字段中都看到了 UTC 日期和时间,我将其全部跟踪到我的网络服务器上的时区设置处于 UTC 时间...我的问题是如何将这些设置为本地用户的日期和时间?所有时间都以 UTC 格式存储在 MySQL 服务器上。
我有用户城市、地区(省/州)和国家。最坏的情况是我想在 PHP 默认时区显示日期和时间。
我该怎么做?
【问题讨论】:
我在我的服务器上的所有日期/时间字段中都看到了 UTC 日期和时间,我将其全部跟踪到我的网络服务器上的时区设置处于 UTC 时间...我的问题是如何将这些设置为本地用户的日期和时间?所有时间都以 UTC 格式存储在 MySQL 服务器上。
我有用户城市、地区(省/州)和国家。最坏的情况是我想在 PHP 默认时区显示日期和时间。
我该怎么做?
【问题讨论】:
您可以使用此函数,并将用户的位置“珀斯,华盛顿州,澳大利亚”作为地址传递给它。
您可以让它返回服务器时区和默认 php 时区之间的偏移量,而不是在失败时返回 0。
您可能希望将其存储在会话变量中,并且仅在变量为空时调用该函数,这将提高页面呈现的速度。
/**
* This function finds the geocode of any given place using the geocoding service of yahoo
* @example getGeoCode("White House, Washington");
* @example getGeoCode("Machu Pichu");
* @example getGeoCode("Dhaka");
* @example getGeoCode("Hollywood");
*
* @param string address - something you could type into Yahoo Maps and get a valid result
* @return int timeZoneOffset - the number of seconds difference between the user's timezone and your server's timezone, 0 if it fails.
*/
function getTimeZoneOffset($address) {
$_url = 'http://api.local.yahoo.com/MapsService/V1/geocode';
$_url .= sprintf('?appid=%s&location=%s',"phpclasses",rawurlencode($address));
$_result = false;
if($_result = file_get_contents($_url)) {
preg_match('!<Latitude>(.*)</Latitude><Longitude>(.*)</Longitude>!U', $_result, $_match);
$lng = $_match[2];
$lat = $_match[1];
$url = "http://ws.geonames.org/timezone?lat={$lat}&lng={$lng}";
$timedata = file_get_contents($url);
$sxml = simplexml_load_string($timedata);
$timeZoneOffset = strtotime($sxml->timezone->time) - time();
return $timeZoneOffset;
}
else
return 0;
}
代码改编自 Time Engine,一个 LGPL php 类。
【讨论】:
在 MySQL 中,当您从数据库中选择数据时,您可以使用函数 CONVERT_TZ 将所有日期转换为当前时区。另一个*线程讨论how to convert time zones using PHP 5's DateTime class.
【讨论】: