PHP - 处理DateTime变量并创建范围

时间:2016-02-03 18:43:55

标签: php arrays date datetime

我想从开始日期到结束日期创建一个DateTime变量数组。我正在使用以下函数来创建值数组。

<?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;
     }
  }?>

当我询问2016-01-01到2016-01-06的阵列时,结果数组是正确的:

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

问题:

如果期限是2016-01-06到2016-01-09,则数组完全错误。

From: 2016-01-06
To: 2015-12-31
Number of dates: 0

我错过了什么?

支持

您可以使用以下代码测试该功能。

<?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>";
    }

?>

修改

我注意到,如果当天的号码是9而不是09,那就有效......

1 个答案:

答案 0 :(得分:1)

当您第一次实例化DataTime对象时,看起来您遇到了类型转换问题,如To日期不正确的输出中所示:

From: 2016-01-06
To: 2015-12-31
Number of dates: 0

将from和to变量指定为字符串显式地实例化DateTimes:

$yearFrom = '2016'; $monthFrom = '01'; $dayFrom = '06';
  $yearTo = '2016'; $monthTo = '01'; $dayTo = '09';

输出:

From: 2016-01-06
To: 2016-01-09
Number of dates: 4
2016-01-06,2016-01-07
2016-01-07,2016-01-08
2016-01-08,2016-01-09