Using DateTime :: CreateFromFormat to Create a Date Object

I have a date string:

25/08/2012 

And here I am trying to convert it to a DateTime object in order to store it in a MySQL database. My backend schema has DateOfPrint date columns ready to receive this data.

Here is what I tried:

 $eventDate = DateTime::createFromFormat('d/m/y', $fecha->innertext); echo $eventDate; 

The echo statement does not display anything on the screen, and when you try to save it to the database, nothing is saved in this column.

Any suggestions?

+4
source share
5 answers

Your $eventDate contains a boolean (false) that prints as an empty string.

You need to use uppercase Y.

Y Full numeric representation of the year, 4 digits Examples: 1999 or 2003
y Two-digit representation of the year Examples: 99 or 03

And you need to call DateTime :: format () ;
eg.

 <?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('Ym-d'); 

prints

 2012-08-25 
+10
source

You need to format it for the 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( 'Ym-d'); // I think this is the correct format 

Then you can use $eventDate to save the date in the database.

+3
source

$eventDate is an object, not a string. You will need to access the properties of the element in your code in order to be able to correctly insert it into the table or echo. In this note, you can use var_dump($eventDate); which should show you everything you need to know about the object.

You can reference PHP docsm in the DateTime class to get the available properties and see which one best suits your needs.

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

short answer

 $st_time = date('Ymd H:i',$yourdate); 

if you want to use only the day of the month and year, use

 $st_time = date('Ym-d',$yourdate); 
0
source

All Articles