format_date()不会通过默认站点时区调整时区偏移量,甚至不会将时区字符串作为参数添加。
下面是代码,代码底部是注释掉的输出。使用format_date有两个示例,最后一个示例是我必须要做的才能获得正确的显示时间。
有关如何使用format_date()处理时区的任何想法吗?
header('content-type: text/plain');
// utc_str as it would come from the db of a date field
$utc_str = '2011-09-01 14:00:00';
// converting to a unix timestamp
$timestamp = strtotime($utc_str);
// first print with format_date, note default site timezone is America/New_York
print 'format_date($timestamp, "custom", "Y-m-d h:s:i"): '. format_date($timestamp, 'custom', 'Y-m-d h:s:i') ."\n";
// next print date by actually setting the timezone string in the argument
// Result:
$tz_str = 'America/New_York';
print 'format_date($timestamp, "custom", "Y-m-d h:s:i", "America/NewYork"): '. format_date($timestamp, 'custom', 'Y-m-d h:s:i', $tz_str) ."\n";
// this is the only way i could get it working
$date = new DateTime($product->field_class_date['und'][0]['value'], new DateTimeZone(date_default_timezone_get()));
$offset = $date->getOffset();
$formatted = date('Y-m-d h:s:i', ($timestamp + $offset));
print $formatted;
/** This is the output
format_date($timestamp, "custom", "Y-m-d h:s:i"): 2011-09-01 02:00:00
format_date($timestamp, "custom", "Y-m-d h:s:i", "America/NewYork"): 2011-09-01 02:00:00
2011-09-01 10:00:00
*/
答案 0 :(得分:3)
你解决它的方式是正确的。如果您使用PHP 5.3或更高版本,您可以使用DateTime::add方法并简单地添加偏移量,而不像我在下面那样创建时间戳。
$utcTimezone = new DateTimeZone('UTC');
$timezone = new DateTimeZone('America/New_York');
$dateTime = new DateTime('2011-09-01 14:00:00', $timezone);
$offset = $timezone->getOffset($dateTime);
print date('Y-m-d H:i:s', $dateTime->format('U') + $offset);