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"; } } ?>