Zend - The PHP Company




Date & Time

Add Code


nextmonth  

Type: code fragment
Added by: rktaxali
Entered: 30/01/2006
Last modified: 02/12/2005
Rating: - (fewer than 3 votes)
Views: 3363
nextmonth() returns a time number corresponding to the date one month from the passed time. It is different from strtotime("next month"). Function takes care of the leap year. E.g. for Jan 31, 2000, strtotime("next month") returns 2000-03-02 whereas nextmonth() returns 2000-02-29


<?php

/* nextmonth returns a time number corresponding to 
   the date one month from the passed time. It is different 
   from strtotime("next month"). Function takes care of the leap year. 
   
   E.g. for Jan 31, 2000, strtotime("next month") returns 2000-03-02
                           whereas nextmonth() returns 2000-02-29
                        
*/
function nextmonth($time=NULL) {
    if (! isset(
$time)) { 
        
$time time(); 
    }
    
    
$year date("Y",$time) ; 
    
$month date("n",$time) ; 
    
$day =  date("j",$time) ; 
    
    if ( 
$day <=28 or ($day <=29 and date("L",$time)) ) {
        return 
strtotime("next month",$time) ; 
    }
    
// create date for the next month 
    
$month++; 
    if (
$month==13) {
        
$month=1
        
$year++; 
        
// All dates are valid in Jan
        
return mktime(0,0,0,$month,$day,$year)  ;  
    }    
    
    
// New date is $year, $month, $day. Is it valid 
    
while (! checkdate($month,$day$year)) {
        
$day--; 
    }
    return 
mktime(0,0,0,$month,$day,$year)  ;  
}

?>


Usage Example


$Reftime= mktime(0,0,0,1,31,2006); 
$Startdate=  date("Y-m-d",$Reftime) ; 

$str = "next month"; 
$strtime = strtotime($str, $Reftime) ; 
$newdate = date("Y-m-d",$strtime ) ; 
// Displays 2006-03-03
echo "<BR>Ref: $Startdate,  Str: $str;  and new date: $newdate";

$str = "+1 month"; 
$strtime = strtotime($str, $Reftime) ; 
$newdate = date("Y-m-d",$strtime ) ; 
// Displays 2006-03-03
echo "<BR>Ref: $Startdate,  Str: $str;  and new date: $newdate";

$nextmonthdate = nextmonth($Reftime) ; 
// Displays 2006-02-28
echo "<BR>Next month using nextmont(): Ref: $Startdate, Next Month:" .  date("Y-m-d",$nextmonthdate) ; 


Rate This Script





Search



This Category All Categories