[ACCEPTED]-Using DateTime::CreateFromFormat to create a date object-datetime

Accepted answer
Score: 11

Your $eventDate contains a boolean(false) which is 2 printed as empty string.

You need to use 1 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();

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


Score: 3

You need to format it for a MySQL column 2 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 1 $eventDate to save the date to the database.

Score: 1

$eventDate is an object, not a string. You will need 8 to access the properties of the element 7 in your code to be able to correctly insert 6 it's value into a table or echo it out. On 5 that note, you could use a var_dump($eventDate); which should show 4 you all there is to know about the object.

You 3 can reference the PHP docsm on the DateTime class to get the available 2 properties and see which one best fits your 1 needs.

Score: 0
$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);
echo $eventDate->format('Y-m-d');


Score: 0

short answer

$st_time =  date('Y-m-d H:i',$yourdate);

if you want only day month 1 and year use this

$st_time =  date('Y-m-d',$yourdate);

More Related questions