Incorrect month (February) - DateTime :: createFromFormat

Converting a date from a string returns incorrect values ​​for the second month (February):

$dtformat = 'Y-m-01';
$curDate = DateTime::createFromFormat('Y-m', '1996-02');
print_r($curDate);
$dt     = $curDate->format($dtformat);
echo $dt."\n";

Instead of "1996-02-01," it returns "1996-03-01." This is an array $currDate:

DateTime Object ( 
    [date] => 1996-03-02 01:19:01 
    [timezone_type] => 3 
    [timezone] => America/New_York 
)

All other months are working fine. What am I missing here?

Thank!

+3
source share
2 answers

This is a bug according to this post .

Cause. . When we do not specify a date createFromFormat, it will be considered the default by default. So in this case it will be 1996-02-31that which does not exist, and therefore it will take the next month.

Solution: You must provide a day to avoid this scenario.

$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m-d",$date."-01");
echo $d->format("Y-m");
+8

:

$curDate = DateTime::createFromFormat('Y-!m'), '1996-02');
+1

All Articles