I'm a little unsure why this is not able to find the last day of the previous month. Every steps seems to be working correctly, except when the final date is created.
<?php $currentMonth = date('n'); $currentYear = date('Y'); if($currentMonth == 1) { $lastMonth = 12; $lastYear = $currentYear - 1; } else { $lastMonth = $currentMonth -1; $lastYear = $currentYear; } if($lastMonth < 10) { $lastMonth = '0' . $lastMonth; } $lastDayOfMonth = date('t', $lastMonth); $lastDateOfPreviousMonth = $lastYear . '-' . $lastMonth . '-' . $lastDayOfMonth; $newLastDateOfMonth = date('F j, Y', strtotime($lastDateOfPreviousMonth)); ?>
$lastDateOfPreviousMonth
is returning 2012-09-30 as expected; however, after trying to convert it to September 30, 2012 - $newLastDateOfMonth
is returning October 1, 2012. Where do I seem to be going wrong?
EDIT: If using date("t/m/Y", strtotime("last month"));
or date('Y-m-d', strtotime('last day of previous month'));
will either of these still be viable given 2013-01-01, i.e. will they account for the change in year?
php $dt = "2008-02-23"; echo 'First day : '. date("Y-m-01", strtotime($dt)). ' - Last day : '. date("Y-m-t", strtotime($dt)); ?>
The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.
previous month means the month or months immediately preceding the month for which a monthly report is due from qualified public depositories.
echo date('Y-m-d', strtotime('last day of previous month')); //2012-09-30
or
$date = new DateTime(); $date->modify("last day of previous month"); echo $date->format("Y-m-d");
Later edit: php.net documentation - relative formats for strtotime(), DateTime and date_create()
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