PHP天差计算错误

bla*_*d Ψ 6 php date php-5.3

我有一些PHP代码来计算两个特定日期之间的天数.差异不应计入星期日和星期六.此外,我有一系列日期,其中包括假期,也需要跳过.

我给出了开始日期01-05-2015和结束日期01-06-2015.我把五月份的整个日子作为阵列.因此差异应该是1天.但我得到的输出为7.问题是什么?这是代码.

function dateRange($first, $last) {
    $dates = array();
    $current = strtotime($first);
    $now = $current;
    $last = strtotime($last);
    while( $current <= $last ) {
        if (date('w', $current) != 0){
            $dates[] = date('d-m-Y', $current);
        }
        $current = strtotime('+1 day', $current);
    }
    unset($dates[0]);
    return $dates;
}


$datea = "01-05-2015";
$date = "01-06-2015";
$hdsarray = array("1-05-2015","2-05-2015","4-05-2015","5-05-2015","7-05-2015","8-05-2015","9-05-2015","11-05-2015","12-05-2015","14-05-2015","15-05-2015","16-05-2015","18-05-2015","19-05-2015","21-05-2015","22-05-2015","23-05-2015","25-05-2015","26-05-2015","28-05-2015","29-05-2015","30-05-2015");

$datesarray = dateRange($datea, $date);
$result = array_diff($hdsarray,$datesarray);
$date_diff = sizeof($result);

echo $date_diff;
Run Code Online (Sandbox Code Playgroud)

kam*_*pal 3

我能看到的唯一问题是 的使用array_diff,它实际上包括被函数排除的周六和周日dateRange(如果在假期列表中找不到的话)。

相反,您可以在函数中传递假期日期dateRange,然后在那里进行过滤。

function dateRange($first, $last, $excludeDates) {
    $dates = array();
    $current = strtotime($first);
    $now = $current;
    $last = strtotime($last);
    while( $current <= $last ) {
        if (date('w', $current) != 0 && date('w', $current) != 6 && !in_array(date('j-m-Y', $current), $excludeDates)){
            $dates[] = date('d-m-Y', $current);
        }
        $current = strtotime('+1 day', $current);
    }
    return $dates;
}

$datea = "01-05-2015";
$date = "01-06-2015";
$hdsarray = array("1-05-2015","2-05-2015","4-05-2015","5-05-2015","7-05-2015","8-05-2015","9-05-2015","11-05-2015","12-05-2015","14-05-2015","15-05-2015","16-05-2015","18-05-2015","19-05-2015","21-05-2015","22-05-2015","23-05-2015","25-05-2015","26-05-2015","28-05-2015","29-05-2015","30-05-2015");
$datesarray = dateRange($datea, $date, $hdsarray);print_r($datesarray);
Run Code Online (Sandbox Code Playgroud)

结果:

Array
(
    [0] => 06-05-2015
    [1] => 13-05-2015
    [2] => 20-05-2015
    [3] => 27-05-2015
    [4] => 01-06-2015
)
Run Code Online (Sandbox Code Playgroud)

所有 5 个日期都出现在结果中,不包括星期六、星期日,也不在假期列表中。