我總是默認時區設置爲GMT
# store all data internally as GMT:
# local tz 1 \
# local tz 2 + <-> webservice.php <-> gmt tz
# local tz 2/
date_default_timezone_set('Zulu');
if(! defined('DATE_FORMAT')) define ('DATE_FORMAT', 'Y-m-d H:i:s');
然後渲染GMT到本地時區中的「視圖「層。當地時區是一個需要解決的主要問題,尤其是夏時制。 :-)
#####################################################
# TIME UTILS
#####################################################
# STORE ALL TIME DATA AS GMT, ALONG WITH THE ORIGINAL TIME ZONE
# format date string referencing one timezone to another timezone, eg
# 'Zulu' -> 'America/Chicago'
# internally, store all data as GMT,
# where each person has a different view of data
# NOTE: full datetime is require, because of dst
function datetime_convert($datestr, $from, $to, $format = null) {
if (! $from) {
error_log("no timezone 'from'");
return $datestr;
}
if (! $to) {
error_log("no timezone 'to'");
return $datestr;
}
if (! $format) {
$format = DATE_FORMAT; # defined above
}
$date = date_parse($datestr);
#print_r($date);
$dtime = new DateTime();
# input in $from timezone
$dtime->setTimeZone(new DateTimeZone($from));
$dtime->setDate($date['year'],$date['month'],$date['day']);
$dtime->setTime($date['hour'],$date['minute'],$date['second']);
# output in $to timezone
$dtime->setTimeZone(new DateTimeZone($to));
$newdatestr = $dtime->format($format);
return $newdatestr;
}
# convert dates with a GMT offset to offset == 0
# 2012-01-20T15:52:22.000-05:00 -> 2012-01-20T20:52:22.000Z
function datetime_normalize($datestr) {
$dtime = new DateTime($datestr);
$dtime->setTimeZone(new DateTimeZone('Zulu'));
$newdatestr = $dtime->format(DATE_FORMAT);
return $newdatestr;
}
# convert a local time to GMT
function datetime_to_gmt($datestr, $from, $format = null) {
return datetime_convert($datestr, $from, 'Zulu', $format);
}
# convert a GMT time to local
function datetime_to_local($datestr, $to, $format = null) {
return datetime_convert($datestr, 'Zulu', $to, $format);
}
閱讀:http://php.net/manual/en/function.date-default-timezone-set.php – Berriel
我建議你保存所有日期爲GMT,並轉換到「視圖」層中的特定時區。 –
所以我不得不在我的日期函數之前添加這個...'date_default_timezone_set('America/Cleveland');'?或者我會在紐約?兩者都是東部時區。 – Paul