【问题标题】:Why does DateTime::createFromFormat() fails and returns a boolean in my second example?为什么 DateTime::createFromFormat() 在我的第二个示例中失败并返回布尔值?
【发布时间】:2015-07-23 22:06:37
【问题描述】:

当我运行它时,第一个被正确地创建为日期。第二个失败,返回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

【问题讨论】:

标签: php string datetime format


【解决方案1】:

查看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 的错误信息在哪里这么简单! (我认为Hour can not be higher than 12 是一个很好的提示:)
  • 感谢您提供有关DateTime::getLastErrors()的信息
【解决方案2】:

h改成大的H,因为小的是12小时制,大的是24小时制。

您可以在manual 中查看所有格式。并从那里引用:

小时的 12 小时格式,前导零从 01 到 12
小时的 24 小时格式,小时的前导零从 00 到 23

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

【讨论】:

  • 别管你有 Y-m-d h:m:s ...两个 m 的事实...第二个应该是 i 分钟。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2014-11-20
    • 1970-01-01
    • 2017-08-27
    • 2014-03-20
    • 2013-09-02
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    相关资源
    最近更新 更多