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

时间:2013-10-25 07:44:14

标签: php

我一直在阅读关于SO的所有相关问题,但我仍然不明白我的错误在哪里。

在我的wordpress网站上,我有一些帖子,其中包含我需要显示的日期,我使用此代码:

$date = DateTime::createFromFormat('Ymd', '20071005');
/*error here*/ $year = $date->format('Y');
echo $year;

信息显示正确,我的代码在我看来是连贯的面向对象的风格。然而,我无法摆脱这个信息:

Fatal error: Call to a member function format() on a non-object in 
/homez.763/frommeto/www/temp/wp-content/themes/fmty/page-listspace.php on line 23

你能看出有什么问题吗?可能是与服务器运行的php版本有关的东西?我使用的是PHP 5.4.1

修改

var_dump($ date)返回

object(DateTime)#84 (3) {
  ["date"]=>
  string(19) "2007-10-05 10:44:57"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

1 个答案:

答案 0 :(得分:1)

我复制并粘贴了你的代码,它运行得很好。我正在使用php5.4.11.

如果您正在尝试显示年份,就像在您的示例中一样,您可以使用strtotime()date()

$date = strtotime('20071005') ;
$year = date('Y', $date) ; 

或者,更简洁:

$year = date('Y',strtotime('20071005')) ;
相关问题