DateTime::createFromFormat("Y/m") will create bad date
Description
The following code:
<?php
echo "January: " . (\DateTime::createFromFormat("Y/m", "2022/01"))->format("Y-m-d") . PHP_EOL;
echo "February: " . (\DateTime::createFromFormat("Y/m", "2022/02"))->format("Y-m-d") . PHP_EOL;
echo "April: " . (\DateTime::createFromFormat("Y/m", "2022/04"))->format("Y-m-d");
Resulted in this output:
January: 2022-01-30
February: 2022-03-02
April: 2022-04-30
But I expected this output instead:
January: 2022-01-01
February: 2022-02-01
April: 2022-04-01
or
January: 2022-01-31
February: 2022-02-28
April: 2022-04-30
PHP Version
PHP 7.4 - PHP 8.0
Operating System
No response
If you don't specify the day, the current day is assumed. That is 30, so the second example is (\DateTime::createFromFormat("Y/m/d", "2022/02/30"))->format("Y-m-d") and this is supposed to yield 2022-03-02, because February has only 28 days (this year), and so overflow occurs as usual for ext/date.
I'm really wondering whether it makes sense to default to the current day instead of the first of a month when parsing a date containing month and/or year information, but no day. Similarly defaulting to the current month when the date contains a year, but no month. Could be just January by default.
(Same also for the time of a day - can just default to 0 for unspecified fields)
@derickr Is there any reason why it has to work this way? To me it just seems like a constant source of confusion.
(But this would be a FR, not a bug)
From the docs:
If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.
If format contains the character !, then portions of the generated time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch.
The Unix epoch is 1970-01-01 00:00:00 UTC.
So you can choose which behavior you want to have. The OP is looking for https://3v4l.org/8pQRO. Changing the default would be a serious and unnecessary BC break.
Thanks, I wasn't aware, but it's not exactly intuitive, I think.
I agree that it's not intuitive, but it's what we have. :)