I am using following codes to display start and end dates of current month.
function firstOfMonth() {
return date("m/d/Y", strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
}
function lastOfMonth() {
return date("m/d/Y", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
}
$date_start = firstOfMonth();
$date_end = lastOfMonth();
echo $date_start;
echo $date_end;
Question: How to get start and end dates of all months in a range of date given
For Eg:
function daterange($startdate,$enddate)
{
...
...
...
}
Expected result be array of start and end dates of each month between date range of $startdate开发者_JS百科
and $enddate
.
Help me how to do this....
<?php
//Function to return out start and end dates of all months in a date range given
function rent_range($start_date, $end_date)
{
$start_date = date("m/d/Y", strtotime($start_date));
$end_date = date("m/d/Y", strtotime($end_date));
$start = strtotime($start_date);
$end = strtotime($end_date);
$month = $start;
$months[] = date('Y-m', $start);
while($month < $end) {
$month = strtotime("+1 month", $month);
$months[] = date('Y-m', $month);
}
foreach($months as $mon)
{
$mon_arr = explode( "-", $mon);
$y = $mon_arr[0];
$m = $mon_arr[1];
$start_dates_arr[] = date("m/d/Y", strtotime($m.'/01/'.$y.' 00:00:00'));
$end_dates_arr[] = date("m/d/Y", strtotime('-1 minute', strtotime('+1 month',strtotime($m.'/01/'.$y.' 00:00:00'))));
}
//to remove first month in start date and add our start date as first date
array_shift($start_dates_arr);
array_pop($start_dates_arr);
array_unshift($start_dates_arr, $start_date);
//To remove last month in end date and add our end date as last date
array_pop($end_dates_arr);
array_pop($end_dates_arr);
array_push($end_dates_arr, $end_date);
$result['start_dates'] = $start_dates_arr;
$result['end_dates'] = $end_dates_arr;
return $result;
}
$start_date = '2011-07-29';
$end_date = '2012-03-31';
$res = rent_range($start_date, $end_date);
echo "<pre>";
print_r($res);
echo "</pre>";
?>
My Above Function will give the month range display of dates within a given range. This function would be useful for monthly rent calculation as indian tradition.
It may help some one else....
Have a look at date function and scroll to format character t
which gives you the number of days. Start date will always be 1 :-)
Doing this in a loop for the number of months between the two dates and storing the values in an array is up to you
function firstAndLast($d=''){
$d = $d?$d:time();
$f = mktime(0,0,0,date("n",$d),1,date("Y",$d));
$l = mktime(0,0,0,date("n",$d),date("t",$d),date("Y",$d));
return array($f,$l);
}
list($first,$last) = firstAndLast();
echo date("d/m/Y",$first)." ($first) - ".date("d/m/Y",$last)." ($last)";
You can pass a timestamp to the function or leave it blank and it will pick up the current time
精彩评论