Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: Call to a member function format() on a non-object

Tags:

php

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"
}
like image 951
pessimo Avatar asked Jan 30 '26 12:01

pessimo


1 Answers

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')) ;
like image 115
jeff Avatar answered Feb 02 '26 01:02

jeff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!