PHP 5.2.12-在DateTime对象上设置时区


PHP 5.2.12 - Setting the Time Zone on a DateTime Object

和往常一样,我阅读了setTimeZone的手册页面,并在谷歌上搜索了以前的任何解决方案,但到目前为止,运气不佳。

我有两个服务器,一个运行PHP 5.3(服务器A),另一个运行PHP5.2(服务器B)。两者的PHPinfo都显示启用了日期/时间支持,并且有一个时区数据库。

然而,当将脚本从服务器a迁移到服务器B时,我开始收到错误消息

致命错误:在非对象上调用成员函数format()

参考

$startdate = $startdate->format("c");

为了测试出了什么问题,我在两台服务器上都运行了以下脚本:

$startdate = '2014-05-05 10:00:00';
echo "Start: " . $startdate ."<br/>";
$tzone = new DateTimeZone('Europe/London');
echo "Tzone: " . print_r($tzone, true) ."<br/>";
$dateobj = new DateTime($startdate, $tzone);
echo "Date Obj: " . print_r($dateobj, true) ."<br/>";
$formatted = $dateobj->format("c");
echo "Formatted: " . print_r($formatted, true) ."<br/>";
$utzone = new DateTimeZone('UTC');
echo "UTzone: " . print_r($utzone, true) ."<br/>";
$utc = $dateobj->setTimeZone($utzone);
echo "UTC: " . print_r($utc, true) ."<br/>";
$formatted2 = $utc->format("c");
echo "Formatted UTC: " . print_r($formatted2, true) ."<br/>";

从服务器A(PHP 5.3)我得到

Start: 2014-05-05 10:00:00
Tzone: DateTimeZone Object ( ) 
Date Obj: DateTime Object ( [date] => 2014-05-05 10:00:00 [timezone_type] => 3 [timezone] => Europe/London ) 
Formatted: 2014-05-05T10:00:00+01:00
UTzone: DateTimeZone Object ( ) 
UTC: DateTime Object ( [date] => 2014-05-05 09:00:00 [timezone_type] => 3 [timezone] => UTC ) 
Formatted UTC: 2014-05-05T09:00:00+00:00 

从服务器B(PHP 5.2)我得到

Start: 2014-05-05 10:00:00
Tzone: DateTimeZone Object ( ) 
Date Obj: DateTime Object ( ) 
Formatted: 2014-05-05T10:00:00+01:00
UTzone: DateTimeZone Object ( ) 
UTC: 
Fatal error: Call to a member function format() on a non-object 

事实上,Formatted行包含一个字符串,这表明DateTime对象已填充,而空白的print_r,我认为是由于PHP5.2中在DateTime上使用print_r的记录问题。

然而,据我从文档中所知,PHP5.2中支持setDateTimeZone,所以我不知道为什么这在服务器B上不起作用。

有人能提出建议吗?如果与此相关,则服务器A正在运行Apache和服务器B IIS。

有趣,但解释起来很简单:正如DateTime文档中所解释的,在PHP 5.3之前,setTimezone的返回值是null

在代码中,将setTimezone的结果分配给$utc变量。在PHP 5.3中,$utc现在又是DateTime对象,在PHP 5.2中是null。在下面的一行中,您将尝试在$utc上调用format方法,当然这在PHP5.2中肯定会失败。