I have a string of a date:
25/08/2012
And here I'm trying to convert it to a DateTime object in order to save it to the MySQL database. My backend schema has a DateOfPrint date
column ready to receive this data.
Here's what I've tried:
$eventDate = DateTime::createFromFormat('d/m/y', $fecha->innertext);
echo $eventDate;
The echo
statement doesn't show anything on the screen, and when trying to save it to the database, nothing is saved in that column.
Any suggestions?
Your $eventDate
contains a boolean(false) which is printed as empty string.
You need to use an upper-case Y.
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
And you have to call DateTime::format();
e.g.
<?php
$fecha = new StdClass;
$fecha->innertext = '25/08/2012';
$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);
if ( false===$eventDate ) {
die('invalid date format');
}
echo $eventDate->format('Y-m-d');
prints
2012-08-25
You need to format it for a MySQL column before you can insert it:
// Need upper case Y here, thanks to VolkerK for pointing that out
$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);
$eventDate = $eventDate->format( 'Y-m-d'); // I think this is the correct format
Then you can use $eventDate
to save the date to the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With