[英]PHP date_format() expects parameter 1 to be DateTimeInterface
I want to convert string to date time, but it's not work.. 我想将字符串转换为日期时间,但这不起作用。
<?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');
return 返回
Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given ...
what is the solution ?? 解决办法是什么 ??
date_create_from_format()
returns false when it fails, or a new DateTime instance when it succeeds. 如果失败,则
date_create_from_format()
返回false;如果成功,则返回新的DateTime实例。
Yours is failing because minutes are two-digits, not single-digits. 您的失败,因为分钟是两位数,而不是一位数。 Using
29_11_2016_5_0_15
as a timestring would yield the following error 使用
29_11_2016_5_0_15
作为时间字符串会产生以下错误
A two digit minute could not be found
找不到两位数分钟
So simply, you'll need to use 29_11_2016_5_00_15
as the timestring instead, like this 简而言之,您需要使用
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>";
}
The output from the above snippet would be 2016-11-29
, live demo: https://3v4l.org/6om9g 上面的代码片段的输出为
2016-11-29
,实时演示: https : //3v4l.org/6om9g
Using date_get_last_errors()
you'll be able to get the errors given in your DateTime instance. 使用
date_get_last_errors()
您将能够获取DateTime实例中给出的错误。
You must use minutes with two chars, in your code is just one where shoud with leading 0. 您必须将分钟数与两个字符一起使用,在您的代码中,仅以1开头应为0。
so just pad it with leading 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.