wiliam.orazi wiliam.orazi - 6 days ago 5
PHP Question

Finding Last Day of Previous Month in PHP

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?

Answer
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()

Comments