At 2022-09-30 i encountered weird behaviour of DateTime::createFromFormat, for pattern ‘Y-m’ and date ‘2022-02’ it returns 2022-03-02, now i know this is happening cause php will populate missing date values.
But today i wanna write some test cases with pattern !Y-m or Y-m| but i cant reproduce the error because now is 2022-10-03 so $d->createFromFormat('Y-m', '2022-02');
will not overflow to march, so can i somehow force DateTime::createFromFormat to return value as if it was launched on 2022-09-30 ?
I also tried creating new instance of DateTime and call createFromFormat on it, instead of static call:
$d1 = new DateTime('2022-09-30');
$d2 = $d1->createFromFormat('Y-m', '2022-02');
print_r($d2->format('Y-m-d')); // returns 2022-02-03, expected 2022-03-02
Also i am using php 7.4
2
Answers
The definition of createFromFormat (https://www.php.net/manual/en/datetime.createfromformat.php) says that the arguments are in reverse order.
Parsing an incomplete date and defining the missing components user-specifically is possible with the class Dt.
The dateFragment returns only the month and year. A regular expression defines how the fragment is to be interpreted. Regular expressions are far more powerful than normal formatting. The missing information (day, hour, minute) is taken from dateInit.