In PHP, there is a very strange behavior when using the "first day" to change the date.
'first day' ' of'? Sets the day of the first of the current month. ( http://php.net/manual/de/datetime.formats.relative.php )
$currentMonthDate = new DateTime("2014-07-30 10:26:00.000000"); echo $currentMonthDate->format('Ym'); $currentMonthDate->modify('first day'); echo $currentMonthDate->format('Ym');
201407/201407 OK
$currentMonthDate = new DateTime("2014-07-31 10:26:00.000000"); echo $currentMonthDate->format('Ym'); $currentMonthDate->modify('first day'); echo $currentMonthDate->format('Ym');
201407/201408 WHY?
$currentMonthDate = new DateTime("2014-08-01 10:26:00.000000"); echo $currentMonthDate->format('Ym'); $currentMonthDate->modify('first day'); echo $currentMonthDate->format('Ym');
201408/201408 OK
I found this behavior on our production server running PHP 5.2, so I assumed that this is an ancient error, but it occurs in PHP 5.3 ( http://phptester.net/ ) and 5.5 on our test server.
If I use the "first day of this month" in PHP 5.2, the same behavior occurs. In PHP 5.5, the "first day of this month" works as expected.
Is the "first day" a mistake? And how to get the "first day of this month" in PHP 5.2 without doing weird conversions between string and date ?
php datetime
Fabio poloni
source share