为什么在我的第二个示例中 DateTime::createFromFormat() 失败并且 returns 是布尔值?
Why does DateTime::createFromFormat() fails and returns a boolean in my second example?
当我运行第一个被正确创建成一个日期。第二个失败,返回 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');
把h
改大H
,因为小的是12小时制,大的是24小时制。
您可以在 manual 中看到所有格式。引自那里:
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
表示现在您的代码失败,因为 12 小时格式中没有 15。
勾选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"
除了其他答案,对于 DateTime
理解的标准格式,您不需要从以下格式创建:
$startDate = "2015-05-12 15:49:06.821289";
$start = new DateTime($startDate);
echo $start->format('m/d/y');
当我运行第一个被正确创建成一个日期。第二个失败,返回 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');
把h
改大H
,因为小的是12小时制,大的是24小时制。
您可以在 manual 中看到所有格式。引自那里:
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
表示现在您的代码失败,因为 12 小时格式中没有 15。
勾选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"
除了其他答案,对于 DateTime
理解的标准格式,您不需要从以下格式创建:
$startDate = "2015-05-12 15:49:06.821289";
$start = new DateTime($startDate);
echo $start->format('m/d/y');