CodeIgniter Forums
get array of months between 2 dates - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: get array of months between 2 dates (/showthread.php?tid=13599)



get array of months between 2 dates - El Forum - 11-28-2008

[eluser]new_igniter[/eluser]
Hello,
Does anyone have a php function for finding the array of months values based on two dates?

for example

Code:
function getMonths('2008-01-01','2008-05-01') {

some code...


}
Thanks!!!


get array of months between 2 dates - El Forum - 11-28-2008

[eluser]xwero[/eluser]
Can you define array of months?

the simplest way i know would be to strtotime the dates if they are in that format and loop until the month in the future is reached.


get array of months between 2 dates - El Forum - 11-28-2008

[eluser]new_igniter[/eluser]
I actually just found and used this:
http://www.dbforums.com/showthread.php?t=1617949

Thanks for your help


get array of months between 2 dates - El Forum - 11-28-2008

[eluser]xwero[/eluser]
My solution
Code:
function get_months($date1, $date2)
{

$date1 = date('Y-m',strtotime($date1));
$date2 = date('Y-m',strtotime($date2));

if($date1 < $date2)
{
   $past = $date1;
   $future = $date2;
}
else
{
   $past = $date2;
   $future = $date1;
}

$months = array();
for($i = $past; $past<=$future; $i++)
{
   $timestamp = strtotime($past.'-1');
   $months[] = date('F Y',$timestamp);
   $past = date('Y-m',strtotime('+1 month',$timestamp));  
}

return $months;
}
The benefit of my code is that the function doesn't care about which date is in the highest.

Another way you could code the function is to let the chronology the dates are added control the sorting of the months, ascending or descending.