Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate, by month, between two specified dates

I have a website that was launched a few months ago. I would like to write some code that will look through every month, since launch, and grab metrics for that month.

My question is: What is the best way to specify a start date, and then iterate by month, all the way up until the current month (or to another specified date).

Does anyone have any suggestions? I'm using PHP and a mySQL database.

like image 786
justinl Avatar asked Dec 18 '09 05:12

justinl


1 Answers

You could use strtotime, to increment the date by +1 month:

$date1 = strtotime('2009-01-01');
$date2 = strtotime('2010-01-01');

while ($date1 <= $date2) {
  echo date('Y-m-d', $date1) . "\n";
  $date1 = strtotime('+1 month', $date1);
}

And if you have PHP >= 5.3.0, you can use DateTime::add with an DateInterval object

Check the above example here.

like image 147
Christian C. Salvadó Avatar answered Sep 24 '22 10:09

Christian C. Salvadó