php 为什么 DateTime::createFromFormat() 在我的第二个示例中失败并返回一个布尔值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30200939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:37:13  来源:igfitidea点击:

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

phpstringdatetimeformat

提问by depperm

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

当我运行它时,第一个被正确创建为日期。第二个失败,返回一个boolean,所以我无法格式化。时间是否超出范围?

//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

Code to reproduce the error

采纳答案by Rizier123

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

将 更改h为大H,因为小是 12 小时格式,大是 24 小时格式。

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

您可以在手册中看到所有格式。和那里的报价:

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

h带有前导零 01 到 12
的小时的12小时格式 H带有前导零 00 到 23 的小时的24 小时格式

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

意味着现在您的代码失败了,因为 12 小时格式中没有 15。

回答by Marc B

Check DateTime::getLastErrors():

检查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"

回答by AbraCadaver

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

除了其他答案之外,对于DateTime您理解的标准格式,您不需要从格式创建:

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