Wednesday, September 14, 2011

Get First and Last date of the Month from given date with php

When working with date ranges we need to find out the month starting and end dates from the given date. here is the PHP function to Get First and Last date of the Month from given date with php

functions used:
list(), split(), date(), mktime(), array()




<?php

# Desc: Funcion to get First and Last date of the Month from Given Date
# Parm: $anyDate ( as YYYY-MM-DD format), $return Format (eg: d-m-Y );
# Return: Array with Two Values of First and Last Date

function first_last_date_of_month($anyDate,$returnFormat)
{
 // separate year, month and date
 list($yr,$mn,$dt)    =    split('-',$anyDate);    
 //Create time stamp of the first day from the give date.
 $timeStamp            =    mktime(0,0,0,$mn,1,$yr);
 //get first day of the given month
 $firstDay            =     date($returnFormat,$timeStamp);    
 //Find the last date of the month and separating it
 list($y,$m,$t)        =     split('-',date('Y-m-t',$timeStamp)); 
 //create time stamp of the last date of the give month
 $lastDayTimeStamp    =    mktime(0,0,0,$m,$t,$y);
 // Find last day of the month
 $lastDay            =    date($returnFormat,$lastDayTimeStamp);
 // return the result in an array format.
 $arrDay                =    array("$firstDay","$lastDay"); 
 return $arrDay;
}

//Usage
$month_range=array();
$month_range=first_last_date_of_month('2011-09-10','d-m-Y');
print $month_range[0];
echo "<br>";
print $month_range[1];

?>


No comments:

Post a Comment