I would like to create an array of DateTime variables from a start to a finish date. I am using the following function to create the array of values.
<?php
class utility
{
// constructor
function __construct()
{
}
/* Creates an array of dates in YYYY-MM-DD format
* INPUT:
* @ From
* @ To
* OUTPUT:
* @ ArrayOfDates
*/
function createDateRangeArray($strDateFrom,$strDateTo)
{
$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
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
}?>
When I ask an array from 2016-01-01 to 2016-01-06 the resulting array is correct:
From: 2016-01-01
To: 2016-01-06
Number of dates: 6
2016-01-01,2016-01-02
2016-01-02,2016-01-03
2016-01-03,2016-01-04
2016-01-04,2016-01-05
2016-01-05,2016-01-06
The Problem:
If the period is from 2016-01-06 to 2016-01-09 the array is completely wrong.
From: 2016-01-06
To: 2015-12-31
Number of dates: 0
What am I missing?
Support
You can test the function using the following code.
<?php
require_once 'utility.php';
$utility = new utility();
$yearFrom = 2016; $monthFrom = 01; $dayFrom = 06;
$yearTo = 2016; $monthTo = 01; $dayTo = 09;
$from = new DateTime($yearFrom.'-'.$monthFrom.'-'.$dayFrom);
echo "<div>From: <b>". $from->format('Y-m-d') . "</b> </div>";
$to = new DateTime($yearTo.'-'.$monthTo.'-'.$dayTo);
echo "<div>To: <b>" . $to->format('Y-m-d') . "</b> </div>";
$arrayDate = $utility->createDateRangeArray($from->format('Y-m-d'),$to->format('Y-m-d'));
echo "<div> Number of dates: " . count($arrayDate) . " </div>" ;
for ($i = 0; $i < count($arrayDate)-1 ; $i++)
{
echo "<div> " . $arrayDate[$i] . "," . $arrayDate[$i+1] . " </div>";
}
?>
EDIT
I have noticed that if the number of the day is 9 instead of 09 it works...