DateTime :: createFromFormat和不完整的日期

I try to use the createFromFormat method for formatting dates. Problem is, when the date is incomplete (missing seconds, minutes or hours) it results into an error. Is there a way to make this work even for incomplete dates like the one below:

$my_sql_date = '2011-01-06 09:39';
$date2 = DateTime::createFromFormat('Y-m-d H:i:s', $my_sql_date);
print_r(DateTime::getLastErrors());

Array ( 
       [warning_count] => 0 
       [warnings] => Array ( ) 
       [error_count] => 1 
       [errors] => Array ( [16] => Data missing ) 
)

Thanks!

Why aren't you using the default __construct?

$my_sql_date = '2011-01-06 09:39';
$date = new DateTime($my_sql_date);
print_r($date);

Will produce

DateTime Object
(
    [date] => 2011-01-06 09:39:00.000000
    [timezone_type] => 3
    [timezone] => US/Pacific
)

You may format it afterwards:

echo $date->format('Y-m-d H:i:s');

which will result in

2011-01-06 09:39:00

You can simply use the DateTime object constructor with your format.

$incompleteData = '2011-01-06 09:39';
$date2 = new DateTime($incompleteData);

The above will work.

Using DateTime::createFromFormat. But with this method your incomplete date will always have to conform to the specified format, so the above method is your best bet.

$incompleteData = '2011-01-06 09:39';
DateTime::createFromFormat('Y-m-d H:i', $incompleteData);