Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Jun 2007
    Posts
    310
    Thanks
    86
    Thanked 3 Times in 3 Posts

    Previous Month of a set month & date

    Hello all,

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

    PHP Code:
    <?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+$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

  • #2
    Regular Coder
    Join Date
    Mar 2006
    Posts
    238
    Thanks
    3
    Thanked 37 Times in 37 Posts
    PHP Code:
    <?php 
    $the_month 
    '01'//Set as Jan
    $the_year '1999'//Set as 1999

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

  • #3
    New Coder
    Join Date
    Aug 2003
    Location
    Derby, UK
    Posts
    97
    Thanks
    0
    Thanked 14 Times in 14 Posts
    No need to reinvent the wheel, check out the manual date functions and you will see that mktime can do this e.g.

    PHP Code:
    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

  • Users who have thanked DaiWelsh for this post:

    SKDevelopment (02-17-2010)

  • #4
    Regular Coder
    Join Date
    Mar 2006
    Posts
    238
    Thanks
    3
    Thanked 37 Times in 37 Posts
    Thanks DaiWelsh. I have completely forgotten about mktime() being able to do the arithmetic. Your code is really much better.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •