date range

Hi,
Could someone explain the following, as i am really puzzled…
this is a function that gives a array of dates, from start to finish date. The function work properly, except for
the entered dates…2012-10-28 <> 2012-10-29…or any range, using these dates.
result:
php example.php
2012-10-28, 2012-10-29, 2012-10-30,
I got a date extra…???

if you try the code and use other dates, like in november or the following 2 days, it works perfect

$labels = DateRangeArray(“2012-10-28”,“2012-10-29”);
foreach($labels as $key => $value){

echo $value . ', ';

}
function DateRangeArray($strDateFrom,$strDateTo) {
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.

// could test validity of dates here but I'm already doing
// that in the main script

$aryRange=array();

$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom) {
    array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
    #echo $iDateFrom . "<br>";
    #echo $iDateTo . "<br>";
    while ($iDateFrom<$iDateTo) {
        $iDateFrom+=86400; // add 24 hours
        #echo $iDateFrom . "after add 86400 " . "<br>";
        date('y-m-d',$iDateFrom) . "<br>";
        array_push($aryRange,date('Y-m-d',$iDateFrom));
    }
}

return $aryRange;

}

I have the same with a simular function, i tried the code on 2 different servers. one with php PHP Version 5.1.6
and one with PHP Version 5.3.3

So if someone can shine his wisdom on this and explain it…i would be very happy.

thanks,
Frank

For me, this code outputs

"2012-10-28, 2012-10-29, "

What timezone are you using?

[php]echo date_default_timezone_get();[/php]

If you add this code to the top of your script, does it work properly?

[php]date_default_timezone_set(‘UTC’);[/php]

Also just want to point out this:

[php]
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
[/php]

Could be done by simply using strtotime()

[php]
$iDateFrom = strtotime($strDateFrom);
$iDateTo = strtotime($strDateTo);
[/php]

If you are still having problems after trying to change to UTC time. Try this:

[php]$iDateFrom+=86400; // add 24 hours[/php]

Replace with:

[php]$iDateFrom = strtotime(’+1 day’, $iDateFrom);[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service