dqwd71332 2013-10-25 07:44
浏览 110

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

I've been reading every related question on SO, but I still don't understand where my error is.

On my wordpress site I have posts with a date that I need to display and I use this code:

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

The information are displayed correctly and my code seems to me coherently object-oriented style. Yet I can't get rid of this message:

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

Can you see if there's anything really wrong? Might it be something related to the version of php the server is running? I'm using PHP 5.4.1

EDIT

var_dump($date) returns

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

1条回答 默认 最新

  • duankui1532 2013-12-09 07:50
    关注

    I copied and pasted your code and it worked just fine. I am using php5.4.11.

    If all you are doing is trying to display the year, as in your example, you could use the strtotime() and date()

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

    Or, more succinctly:

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大