Monday, March 11, 2013

Find date of last day of a month and number of days of a month in PHP


To find date of last day of a month you can use the below line :

  date("j-n-Y", mktime(0, 0, 0, date("m")+1 , date("d")-date("d"), date("Y"))); 

For example, if you have to find last day of Febraury 2012, code goes as below :

 $month='02';
  $year='2012';
  $dtLastDay = date("j-n-Y", mktime(0, 0, 0, $month+1 , date("d")-date("d"),     
   $year));

$dtLastDay will have 29-2-2012.


To calculate number of days in a month, syntax is as below :

  $num = cal_days_in_month(CAL_GREGORIAN, month, year) ; 

For example, if you want number of days in Feb 2012, you can change the above syntax as the follwing one 
  
  $year='2012';
  $num = cal_days_in_month(CAL_GREGORIAN, $month, $year) ; 

 $num will have no. of days ie., 29 in this case