![](/img/trans.png)
[英]date_format() expects parameter 1 to be DateTimeInterface, boolean given
[英]PHP date_format() expects parameter 1 to be DateTimeInterface
我想将字符串转换为日期时间,但这不起作用。
<?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 ...
解决办法是什么 ??
如果失败,则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>";
}
上面的代码片段的输出为2016-11-29
,实时演示: https : //3v4l.org/6om9g
使用date_get_last_errors()
您将能够获取DateTime实例中给出的错误。
您必须将分钟数与两个字符一起使用,在您的代码中,仅以1开头应为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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.