I need to get previous month and year, relative to current date.
However, see following example.
// Today is 2011-03-30
echo date(\'Y-m-d\', strtotim
strtotime
have second timestamp
parameter that make the first parameter relative to second parameter. So you can do this:
date('Y-m', strtotime('-1 month', time()))
//return timestamp, use to format month, year as per requirement
function getMonthYear($beforeMonth = '') {
if($beforeMonth !="" && $beforeMonth >= 1) {
$date = date('Y')."-".date('m')."-15";
$timestamp_before = strtotime( $date . ' -'.$beforeMonth.' month' );
return $timestamp_before;
} else {
$time= time();
return $time;
}
}
//call function
$month_year = date("Y-m",getMonthYear(1));// last month before current month
$month_year = date("Y-m",getMonthYear(2)); // second last month before current month
date("m-Y", strtotime("-1 months"));
would solve this
Have a look at the DateTime class. It should do the calculations correctly and the date formats are compatible with strttotime
. Something like:
$datestring='2011-03-30 first day of last month';
$dt=date_create($datestring);
echo $dt->format('Y-m'); //2011-02
This is because the previous month has less days than the current month. I've fixed this by first checking if the previous month has less days that the current and changing the calculation based on it.
If it has less days get the last day of -1 month else get the current day -1 month:
if (date('d') > date('d', strtotime('last day of -1 month')))
{
$first_end = date('Y-m-d', strtotime('last day of -1 month'));
}
else
{
$first_end = date('Y-m-d', strtotime('-1 month'));
}
If you want the previous year and month relative to a specific date and have DateTime available then you can do this:
$d = new DateTime('2013-01-01', new DateTimeZone('UTC'));
$d->modify('first day of previous month');
$year = $d->format('Y'); //2012
$month = $d->format('m'); //12