Why does DateTime :: createFromFormat () fail and return a boolean in my second example?

When I run this, the first one is correctly created on the date. The second fails, returning boolean , and therefore I cannot format. Is time out of range?

 //works correctly $startDate = "2015-05-06 10:49:20.637133"; $start = DateTime::createFromFormat('Ymd h:m:s.u',$startDate); echo $start->format('m/d/y'); //doesn't work correctly $startDate = "2015-05-12 15:49:06.821289"; $start = DateTime::createFromFormat('Ymd h:m:s.u',$startDate); echo $start->format('m/d/y'); 

Code to reproduce the error

+7
string php datetime format
source share
3 answers

Change h to large h , as small is a 12-hour format and large is a 24-hour format.

You can see all formats in manual . And a quote from there:

h 12 hour clock format with leading zeros 01 to 12
H 24-hour hour format with leading zeros from 00 to 23

So right now, your code is out of order because there is no 15 in the 12-hour format.

+10
source share

Check DateTime::getLastErrors() :

 php > var_dump(DateTime::createFromFormat('Ymd h:m:s',"2015-05-12 15:49:06")); bool(false) php > var_dump(DateTime::getLastErrors()); array(4) { ["warning_count"]=> int(1) ["warnings"]=> array(1) { [19]=> string(27) "The parsed date was invalid" } ["error_count"]=> int(1) ["errors"]=> array(1) { [11]=> string(30) "Hour can not be higher than 12" 
+10
source share

In addition to other answers, for standard formats understood by DateTime , you do not need to create from a format:

 $startDate = "2015-05-12 15:49:06.821289"; $start = new DateTime($startDate); echo $start->format('m/d/y'); 
+2
source share

All Articles