【问题标题】:PHP date_format() expects parameter 1 to be DateTimeInterfacePHP date_format() 期望参数 1 为 DateTimeInterface
【发布时间】:2016-12-24 10:25:27
【问题描述】:

我想将字符串转换为日期时间,但它不起作用..

<?php  
$date = date_create_from_format('d_m_Y_H_i_s', '29_11_2016_5_0_15');
echo date_format($date, 'Y-m-d');

返回

Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given ...

解决办法是什么??

【问题讨论】:

  • 29_11_2016_05_00_15
  • date_create_from_format 返回false,这就是问题所在。如果您不使用带前导零的 24 小时格式,请使用 G 而不是 H。暂时,您必须添加前导零,您可以自己添加。
  • @Qirel 日期格式(day_month_year_hour_minute_second)
  • @Federkun,我遇到了同样的错误

标签: php date datetime date-format


【解决方案1】:

date_create_from_format() 失败时返回 false,或者成功时返回新的 DateTime 实例。

你的失败是因为分钟是两位数,而不是个位数。使用29_11_2016_5_0_15 作为时间字符串会产生以下错误

找不到两位数的分钟

很简单,您需要使用29_11_2016_5_00_15 作为时间字符串,就像这样

// Try to create the datetime instance
if ($date = date_create_from_format('d_m_Y_H_i_s', '29_11_2016_5_00_15')) {
    echo date_format($date, 'Y-m-d');
} else {
    // It failed! Errors found, let's figure out what!
    echo "<pre>";
    print_r(date_get_last_errors());
    echo "</pre>";
}

上述 sn-p 的输出将是 2016-11-29,现场演示:https://3v4l.org/6om9g

使用date_get_last_errors(),您将能够获取 DateTime 实例中给出的错误。

【讨论】:

    【解决方案2】:

    您必须使用带有两个字符的minutes,在您的代码中只有一个应该带有前导0。

    所以只需用前导 0 填充它。

    <?php
    $string = '29_11_2016_5_0_15';
    $array = explode('_', $string);
    $array[4] = str_pad($array[4], 2, 0, STR_PAD_LEFT);
    $string = implode('_', $array);
    $date = date_create_from_format('d_m_Y_H_i_s', $string);
    echo date_format($date, 'Y-m-d');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      相关资源
      最近更新 更多