2013-10-25 84 views
3

我一直在閱讀有關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" 
} 
+0

代碼本身應該可以正常工作(請參閱[this](http://codepad.viper-7.com/EJZXrS))。它必須是一個配置問題。 – NullUserException

+0

你的代碼,運行良好在我的pc.my php版本是5.4.16.try在php.ini中設置時區 – Ramin

+0

如果你添加'print_r(DateTime :: getLastErrors());'緊跟'$ date = DateTime :: createFromFormat('Ymd','20071005');'輸出任何錯誤? – 2013-12-09 07:56:09

回答

1

我複製並粘貼您的代碼和它的工作就好了。我使用php5.4.11.

如果你正在做的是試圖顯示年份,因爲在你的榜樣,您可以使用strtotime()date()

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

或者,更簡潔:

$year = date('Y',strtotime('20071005')) ; 
相關問題