简体   繁体   中英

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.

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

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

// 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

Using date_get_last_errors() you'll be able to get the errors given in your DateTime instance.

You must use minutes with two chars, in your code is just one where shoud with leading 0.

so just pad it with leading 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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM