On some dates, DateTime::createFromFormat incorrect parse date from 'Y-m' format
Description
The following code:
<?php
// I am running it on 2023-01-31 and it failed but if local time is set to 2023-02-01 all works as expected
var_dump(DateTime::createFromFormat('Y-m','2022-02'));
Resulted in this output:
object(DateTime)#6654 (3) {
["date"]=>
string(26) "2022-**03-03** 16:56:07.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
But I expected this output instead:
object(DateTime)#6654 (3) {
["date"]=>
string(26) "2022-**02-28** 16:56:07.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
PHP Version
PHP 8.1.14
Operating System
No response
@peresmishnyk It works as expected. A citation from the doc (https://www.php.net/manual/en/datetimeimmutable.createfromformat.php) All fields are initialised with the current date/time. In most cases you would want to reset these to "zero" (the Unix epoch, 1970-01-01 00:00:00 UTC). You do that by including the ! character as first character in your format, or | as your last.
So without specifying a day, the current "day number" (31) is used. But as February has only 28 days, 3 days overflow to March (not "trimming" to the last day of February, as you are expecting)
You can use ! to change this behaviour:
var_dump(DateTime::createFromFormat('!Y-m','2022-02'));
//=>
object(DateTime)#1 (3) {
["date"]=>
string(26) "2022-02**-01** 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}