Object of class DateTime could not be converted to string

DIM3NSION picture DIM3NSION · Apr 18, 2012 · Viewed 203.7k times · Source

I have a table with string values in the format of Friday 20th April 2012 in a field called Film_Release

I am looping through and i want to convert them in datetime and roll them out into another table. My second table has a column called Films_Date, with a format of DATE. I am receiving this error

Object of class DateTime could not be converted to string

$dateFromDB = $info['Film_Release'];
 $newDate = DateTime::createFromFormat("l dS F Y",$dateFromDB); //( http:php.net/manual/en/datetime.createfromformat.php)

Then I insert $newdate into the table through an insert command.

Why am I be getting such an error?

Answer

Jon picture Jon · Apr 18, 2012

Because $newDate is an object of type DateTime, not a string. The documentation is explicit:

Returns new DateTime object formatted according to the specified format.

If you want to convert from a string to DateTime back to string to change the format, call DateTime::format at the end to get a formatted string out of your DateTime.

$newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
$newDate = $newDate->format('d/m/Y'); // for example