Conversion Error: Converting DateTime Object to String
When attempting to convert a string in the format "Friday 20th April 2012" in a table to a datetime value and inserting it into a second table with a DATE format, you encounter the error "Object of class DateTime could not be converted to string."
To resolve this issue, understand that converting from a string to a DateTime object using DateTime::createFromFormat returns an object, not a string. To change the format and convert the DateTime object back to a string, call DateTime::format at the end of the conversion process.
Here's a revised code snippet:
$dateFromDB = $info['Film_Release']; $newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB); $newDate = $newDate->format('d/m/Y'); // for example
In this revised code, $newDate is first created as a DateTime object using DateTime::createFromFormat. Then, using DateTime::format, it is formatted and converted to a string in the desired 'd/m/Y' format. This string can then be inserted into the second table using an insert command without generating the conversion error.
The above is the detailed content of How to Convert a \'Friday 20th April 2012\' String to a Date Value in PHP?. For more information, please follow other related articles on the PHP Chinese website!