The date conversion from string returns wrong values for the 2nd 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 the $currDate
array:
DateTime Object (
[date] => 1996-03-02 01:19:01
[timezone_type] => 3
[timezone] => America/New_York
)
All other months work fine. What am I missing here?
Thanks!
It's not a bug according to this post.
Cause: When we don't provide date to createFromFormat
it will take as today's date by default. So in this case it will be 1996-02-31
which does not exist & thus it will take a next month.
Solution: Need to provide day to avoid such scenario.
$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m-d",$date."-01");
echo $d->format("Y-m");
Try with this code:
$curDate = DateTime::createFromFormat('!Y-m', '1996-02');
The manual explains:
!
Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to the Unix Epoch
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With