如何在PHP中没有星期日减去两个日期

时间:2016-05-19 09:58:05

标签: php date datetime

我想用php或cakephp函数减去日期, 例如:

$date1 = '2016-05-19';
$date2 = '2016-05-23';

我想在没有星期日的情况下减去日期,例如我想要的结果是3而不是4,因为4 - 1(星期日),

我已经尝试使用新的Datetime php,就像这段代码一样,

$receipt_date   = new DateTime($air_way_bill['AirWayBill']['receive_date']);
$date           = new DateTime($air_way_bill['AirWayBill']['date']);
$difference     = $receipt_date->diff($date);

但结果是4,我如何在该范围之间减去周日? 按照我的意思做任何步骤或方法?

提前感谢...

[CASE CLOSED]:

真答案:

// ============================= 1 ==================== //

$receipt_date   = new DateTime('2016-05-19');
$date           = new DateTime('2016-05-23');
$difference     = $receipt_date->diff($date);

$daterange = new DatePeriod($receipt_date, new DateInterval('P1D'), $date);

$count = 0;

foreach($daterange as $date){
    if(!($date->format("w"))) {
        $count++;
    }
}

echo ($difference->days)-$count;

// ============================================= === //

// ============================= 2 ==================== //

function getSubtrackedDayCountWithoutSundaysButWithAllOtherDaysUsingDateTimeFunctions($startDate, $endDate)
{
    $days = $startDate->diff($endDate, true)->days;
    $sundays = intval($days / 7) + ($startDate->format('N') + $days % 7 >= 7);

    return intval($days)-Sundays;

}

// ============================================= =========== //

// =====================这是我的实验=============== //

        $date = date('Y-m-d', strtotime($air_way_bill['AirWayBill']['date']));
        $receive_date = date('Y-m-d', strtotime($air_way_bill['AirWayBill']['receive_date']));

        $date_diff = round(abs(strtotime($receive_date) - strtotime($date)) / 86400);
        $weeks  = round(abs(strtotime($receive_date) - strtotime($date)) / (86400 * 7));

         echo $date_diff - $weeks;

// ============================================= =========== //

非常感谢...

2 个答案:

答案 0 :(得分:1)

我写了一个函数来做你想要的。

function getSubtrackedDayCountWithoutSundaysButWithAllOtherDaysUsingDateTimeFunctions($startDate, $endDate)
{
    $days = $startDate->diff($endDate, true)->days;
    $sundays = intval($days / 7) + ($startDate->format('N') + $days % 7 >= 7);

    return intval($days)-$sundays;


}

答案 1 :(得分:1)

您可以找到总天数,然后查找该范围内的星期日数。最后从总天数减少这些天数:

<?php    
$receipt_date   = new DateTime('2016-05-19');
$date           = new DateTime('2016-05-23');
$difference     = $receipt_date->diff($date);

$daterange = new DatePeriod($receipt_date, new DateInterval('P1D'), $date);

$count = 0;

foreach($daterange as $date){
    if(!($date->format("w"))) {
        $count++;
    }
}

echo ($difference->days)-$count;

Demo

相关问题