...

View Full Version : Previous Month of a set month & date



stfc_boy
02-17-2010, 09:11 AM
Hello all,

I have a script which finds the next month of the year (and year if it's December)



<?php

$the_month = '01'; //Set as Jan
$the_year = '1999'; //Set as 1999

$temp = $the_month+1;
$the_next_month = str_pad($temp>12 ? $temp-12 : $temp,2,'0',0);
$the_next_year = $temp>12 ? $the_year+1 : $the_year;
echo $the_next_month,'-',$the_next_year;
?>


But I can't work this out for the previous month. Can anyone kindly help?

Thanks

SKDevelopment
02-17-2010, 09:45 AM
<?php
$the_month = '01'; //Set as Jan
$the_year = '1999'; //Set as 1999

$temp = $the_month-1;
$the_prev_month = str_pad($temp<1 ? 12 : $temp,2,'0',0);
$the_prev_year = $temp<1 ? $the_year-1 : $the_year;
echo $the_prev_month,'-',$the_prev_year;
?>

DaiWelsh
02-17-2010, 11:16 AM
No need to reinvent the wheel, check out the manual date functions and you will see that mktime can do this e.g.



echo(date('m-Y',nextmonth(11,2009)).'<br/>');
echo(date('m-Y',nextmonth(12,2009)).'<br/>');
echo(date('m-Y',prevmonth(2,2009)).'<br/>');
echo(date('m-Y',prevmonth(1,2009)).'<br/>');
function nextmonth($intThisMonth,$intThisYear) {
return(mktime(0,0,0,$intThisMonth + 1,15,$intThisYear));
}
function prevmonth($intThisMonth,$intThisYear) {
return(mktime(0,0,0,$intThisMonth - 1,15,$intThisYear));
}


HTH,

Dai

SKDevelopment
02-17-2010, 12:06 PM
Thanks DaiWelsh. I have completely forgotten about mktime() being able to do the arithmetic. Your code is really much better.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum