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


SUBMITTED BY: Guest

DATE: May 2, 2013, 9:45 p.m.

FORMAT: PHP

SIZE: 1.2 kB

HITS: 1104

  1. <?php
  2. function get_months($startstring, $endstring)
  3. {
  4. $time1 = strtotime($startstring); //absolute date comparison needs to be done here, because PHP doesn't do date comparisons
  5. $time2 = strtotime($endstring);
  6. $my1 = date('mY', $time1); //need these to compare dates at 'month' granularity
  7. $my2 = date('mY', $time2);
  8. $year1 = date('Y', $time1);
  9. $year2 = date('Y', $time2);
  10. $years = range($year1, $year2);
  11. foreach ($years as $year) {
  12. $months[$year] = array();
  13. while ($time1 < $time2) {
  14. if (date('Y', $time1) == $year) {
  15. $months[$year][] = date('m', $time1);
  16. $time1 = strtotime(date('Y-m-d', $time1) . ' +1 month');
  17. } else {
  18. break;
  19. }
  20. }
  21. continue;
  22. }
  23. return $months;
  24. }
  25. ?>
  26. <?php
  27. $montharr = get_months('2003-01-04', '2005-09-18');
  28. foreach (array_keys($montharr) as $year) {
  29. foreach ($montharr[$year] as $month) {
  30. print "{$year}-{$month}\n";
  31. }
  32. }
  33. ?>

comments powered by Disqus