Tuesday, November 12, 2013

Just discovered a new way to loop through months, up to the current month. I used to have horrible code like this:

    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();
    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!

No comments: