31 October, 2010

Get all month names between two dates in php

Yesterday i faced a problem regarding date manipulation in php. I had to get all month names between two dates, after some work around, i managed to make it work. I created a function "get_months" and passed two dates i.e. start date and end date to find list of months between the two dates.
Here's the function:

function get_months($date1, $date2) {
//convert dates to UNIX timestamp
$time1 = strtotime($date1);
$time2 = strtotime($date2);
$tmp = date('mY', $time2);

$months[] = array("month" => date('F', $time1), "year" => date('Y', $time1));

while($time1 < $time2) {
$time1 = strtotime(date('Y-m-d', $time1).' +1 month');
if(date('mY', $time1) != $tmp && ($time1 < $time2)) {
$months[] = array("month" => date('F', $time1), "year" => date('Y', $time1));
}
}
$months[] = array("month" => date('F', $time2), "year" => date('Y', $time2));
return $months; //returns array of month names with year
}

Thats it. I hope this helps someone like me.

2 comments:

Rohit Ayare said...

Sudhir Bastakoti's Thanks Sir your code worked like charm for me.

Benjamín Silva said...

Worked like a charm, thank you very much!