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
Why does DateTime::createFromFormat() fails and returns a boolean in my second example?
提问by depperm
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?
当我运行它时,第一个被正确创建为日期。第二个失败,返回一个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');
采纳答案by Rizier123
Change the h
to 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 DateTime
you 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');