Onesinus Saut Onesinus Saut - 6 months ago 16
PHP Question

How to subtract two dates without sunday in php

I want to subtract date with php or cakephp function,
example :


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


i want subtract dates without sunday, from example the result i want is 3, not 4, because 4 - 1 (sunday),

I already try with new Datetime php like this code,

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


but the result is 4, how can i subtract with sunday between that range?
there is any step or way to doing what i mean?

thanks in advance...

Answer

You can find total days, and then find number of sundays in that range. Finally reduce those days from total days:

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