3

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"
}
5
  • The code itself should work fine (see this). It must be a configuration issue. Oct 25, 2013 at 15:48
  • your code, runs good in my pc.my php version is 5.4.16.try to set timezone in php.ini Oct 25, 2013 at 15:51
  • If you add this print_r(DateTime::getLastErrors()); just after $date = DateTime::createFromFormat('Ymd', '20071005'); outputs any error?
    – user1765062
    Dec 9, 2013 at 7:56
  • I had the same issue, but I noticed the code get triggered more than once that caused the issue to get caught. Just put the code in a separate file and verify it whether works or not.
    – SenG
    Jan 24, 2015 at 11:26
  • @SenG true, I ended up separating the calls in different files for other reasons and the problem disappeared, But I still don't know how to achieve multiple calls in the same document...
    – pessimo
    Jan 26, 2015 at 8:30

1 Answer 1

1

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')) ;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.