Get a List of Years and Months in a Date Range with PHP

I can’t find the initial inspiration for this to link to – sorry. I came across a forum post or maybe a blog post where someone needed to do something like return an array of the months (or maybe it was days or something) in a given date range. I had a place where I could’ve potentially used a similar bit of code, so I wrote this, and when I was done, I realized it was much nicer than the code I had started with, but lost the link to go back and post the code there. In the event that this is useful to someone, I’ll post it here :)

UPDATE: Don’t ask me why my WP SyntaxHighlighter plugin refused to preserve the indentation in this code. I haven’t a clue. If you do, post a comment to share the clue.


<?php

function get_months($startstring, $endstring)
{
$time1  = strtotime($startstring);//absolute date comparison needs to be done here, because PHP doesn't do date comparisons
$time2  = strtotime($endstring);
$my1     = date('mY', $time1); //need these to compare dates at 'month' granularity
$my2    = date('mY', $time2);
$year1 = date('Y', $time1);
$year2 = date('Y', $time2);
$years = range($year1, $year2);

foreach($years as $year)
{
$months[$year] = array();
while($time1 < $time2)
{
if(date('Y',$time1) == $year)
{
$months[$year][] = date('m', $time1);
$time1 = strtotime(date('Y-m-d', $time1).' +1 month');
}
else
{
break;
}
}
continue;
}

return $months;
}

?>

And here’s some sample code to make use of it:


<?php

$montharr = get_months('2003-01-04', '2005-09-18');
foreach(array_keys($montharr) as $year)
{
foreach($montharr[$year] as $month)
{
print "{$year}-{$month}\n";
}
}

?>

  • shiva

    Thanks a lot for your help.

  • xxx

    there is a bug in this code, today is 2010-11-30 and when I generate month array from today to 2011-11-18 function return
    2010-11
    2010-12
    2011-01
    2011-03
    2011-04
    2011-05
    2011-06
    2011-07
    2011-08
    2011-09
    2011-10
    2011-11

    without february because february 2011 have just 28 days
    to fix this bug you need to change

    this line
    $time1 = strtotime(date(‘Y-m-d’, $time1).’ +1 month’);
    into this
    $time1 = strtotime(date(‘Y-m’, $time1).’ +1 month’);

  • roman

    $start = $month = strtotime(‘2003-01-04′);
    $end = strtotime(‘2005-09-18′);

    while($month <= $end)
    {
    // there init array using date('M',$month), date('Y',$month) or other
    $month = strtotime(date('Y-n', $month).' +1 month');
    }

  • Hector Juarez

    thanks for your help whit the code, helped me alot