Just discovered a new way to loop through months, up to the current month. I used to have horrible code like this:
for($y=2009;$y<=date("Y");++$y){
  for($m=1;$m<=12;++$m){
    if($y==date("Y") && $m>=date("m"))continue;
    $t = strtotime("$Y-$m-01"); 
    echo date("M_Y",$t)."\n";
    }
  }
If wanting days, you get $t then do $days_in_month = date("t",$t);
Here is my new solution:
$start = strtotime("2009-01-15");
$now = time();
$secs_per_month=(int)((365.25*86400)/12);
for($t=$start;$t<$now;$t+=$secs_per_month){
    echo date("M_Y",$t)."\n";
    }
I.e. choose a day in the middle of the month, and do everything in seconds. Fewer calls to date() and shorter code. Obvious in hindsight!
Tuesday, November 12, 2013
Labels:
date handling,
php
Subscribe to:
Post Comments (Atom)
 
 
No comments:
Post a Comment