Why does DateTime::createFromFormat() fails and re

2020-08-09 10:23发布

问题:

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

//works correctly
$startDate = "2015-05-06 10:49:20.637133";
$start = DateTime::createFromFormat('Y-m-d 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('Y-m-d h:m:s.u',$startDate);
echo $start->format('m/d/y');

Code to reproduce the error

回答1:

Change the h to a big H, since the small one is 12-hours format and the big one is 24-hours format.

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

h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23

Means right now your code fails, because there is no 15 in the 12 hour format.



回答2:

Check DateTime::getLastErrors():

php > var_dump(DateTime::createFromFormat('Y-m-d 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"


回答3:

In addition to the other answers, for standard formats understood by DateTime you don't need to create from a format:

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