Why does DateTime::createFromFormat() fails and returns a boolean in my second example?

吃可爱长大的小学妹 提交于 2019-12-04 23:35:16

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.

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"

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');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!