2012-04-19 113 views
0

此函数返回两个日期之间的日期数组。检查两个日期之间的日期错误,无知

现在,它的工作完全正常,除了一些未知的原因,如果我把它的11月份或3月份作为参数,我得到的数组少一天。其他几个月工作完全正常。我绝对无能为力。

function getListofDatesInRange2($fromDate, $toDate) 
{ 
    $fromDate = str_replace("-","/", $fromDate); 
    $toDate = str_replace("-","/", $toDate); 

    $dateMonthYearArr = array(); 
    $fromDateTS = strtotime($fromDate); 
    $toDateTS = strtotime($toDate); 

    for ($currentDateTS = $fromDateTS; $currentDateTS <= $toDateTS; $currentDateTS += (60 * 60 * 24)) { 
     $currentDateStr = date("m-d-Y",$currentDateTS); 
     $dateMonthYearArr[] = $currentDateStr; 
    } 

return $dateMonthYearArr; 
} 

我重新编写了它,while循环解决了我的问题。 (虽然我不知道这个问题是摆在首位)

function getListofDatesInRange2($fromDate, $toDate) 
{ 
$fromDate = str_replace("-","/", $fromDate); 
$toDate = str_replace("-","/", $toDate); 

$dateMonthYearArr = array(); 
$fromDateTS = strtotime($fromDate); 
$toDateTS = strtotime($toDate); 

array_push($dateMonthYearArr, date('m-d-Y', $fromDateTS)); 
while($fromDateTS < $toDateTS) { 
    $fromDateTS += 86400; 
    array_push($dateMonthYearArr, date('m-d-Y', $fromDateTS)); 
} 
return $dateMonthYearArr; 

}

+0

可能重复的[如何找到两个指定日期之间的日期?](http://stackoverflow.com/questions/2736784/how-to-find-the-dates-between-two-specified-date) – Treffynnon 2012-04-19 21:44:00

回答

1

几乎可以肯定,这是由一些傻瓜多年前谁决定这一天应该在一个月之间进去造成的,这一年,而不是一些逻辑排序(大多数计算中的大端,英国英语中的小端)。

取而代之的是,在将它们输入strtotime之前,将输入日期的格式为YYYY-mm-dd。这将确保您始终获得正确的日期。

为了测试这的确是你的问题,请尝试:

$fromDateTS = strtotime($fromDate); 
echo date("m-d-Y",$fromDateTS); 

确保所显示的日期是一样的,你投入的日期可能是,它不是。

+0

感谢有趣的答案,但不幸的是,测试失败了。但是我重写了它,现在它工作正常。如果你有兴趣,请检查一下。我编辑了我的问题 – volk 2012-04-19 21:57:38

相关问题