PHP天差计算错误

标签 php date php-5.3

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

我将开始日期设为 01-05-2015,将结束日期设为 01-06-2015。我把 5 月份的所有日子都作为数组给出。因此,差异应为 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;

最佳答案

我能看到的唯一问题是 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);

结果:

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

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

关于PHP天差计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30726700/

相关文章:

php - 如何撤消命令 "php artisan config:cache"的影响?

angular - 日期格式更改 Angular 2

java - 使用滚动方法设置日历字段

php - 将字符串分成几部分,返回所有字符

php - 什么是可以在 PHP 5.3 上解析和重建 SQL 查询的优秀查询生成器?

javascript - 使用模式对话框登录表单让我登录 php 函数

php - cakephp 3 在记录时使用范围

php - 在 webdriver 中呈现 HTML 字符串或本地 html 文件

Spring Data MongoDB 与 Java 8 LocalDate MappingException

soap - PHP 通过浏览器处理 SOAP 请求很慢,但在命令行上很好