tirso
tirso

Reputation: 253

php loop by date of the month

Provided the code stated below, the output are (see below). My question is why after 2009/11/01 it follow's by 2009/11/30 and 2009/12/30 instead of 2009/12/01. From 2009/06/01 ~ 2009/11/01 there is no problem.

output
2009/06/01
2009/07/01
2009/08/01
2009/09/01
2009/10/01
2009/11/01
2009/11/30
2009/12/30

my code

<?php

$startdate = "2009/06/01";
$enddate = "2009/12/31";

$start = strtotime($startdate); 
$end = strtotime($enddate); 

$currentdate = $start; 
while($currentdate < $end)
{
    $cur_date = date('Y/m/d',$currentdate);
    $month = date('m', $currentdate); 
    $year = date('Y', $currentdate); 
    $monthLength = daysOfMonth($month, $year); 
    $currentdate += $monthLength; 

    echo $cur_date . "<br />";  
}


function daysOfMonth($month, $year)
{
    return (86400 * date("t", strtotime($year."-".$month."-01")));
} 

?>

Upvotes: 2

Views: 3966

Answers (1)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146450

<?php

$startdate = "2009/06/01";
$enddate = "2009/12/31";

$start = strtotime($startdate);
$end = strtotime($enddate);

$currentdate = $start;
while($currentdate < $end)
{
        $cur_date = date('Y/m/d', $currentdate);

        $currentdate = strtotime('+1 month', $currentdate);

        echo $cur_date . "<br />";
}

?>

Upvotes: 1

Related Questions