无法转换类DateTime的对象

I can see that there are many questions along these lines but I am very confused as to why the following does not work, taken straight from the PHP docs:

$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $tempDate;

The error:

PHP Catchable fatal error: Object of class DateTime could not be converted to string.

In fact every example in the docs gives me this error. Any ideas?

You can't echo the DateTime object directly. You have to use the format method to get the date and / or time part:

$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $tempDate->format('Y-m-d H:i:s');
// NOT echo $tempDate!!!

demo: http://ideone.com/IyqRWj

If you want to see the details of the object (for debug) you can use var_dump:

$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
var_dump($tempDate);

The error message:

PHP Catchable fatal error: Object of class DateTime could not be converted to string.

is self-explanatory. The statement:

echo $tempDate;

attempts to print a DateTime object. The echo() language construct expects a string, you pass it a DateTime object. The DateTime class does not implement the __toString() magic method and PHP doesn't know how to convert a DateTime object to string.

There are so many ways to represent a DateTime object as string and all of them are handled by the DateTime::format() method.


In fact every example in the docs gives me this error.

In fact, every example in the documentation of DateTime::createFromFormat() reads:

echo $date->format('Y-m-d');

which is a different thing that echo $date;.


Any ideas?

Read the documentation of DateTime and DateTime::format() carefully.