0

In php i am using this code to calculate difference between two dates in number of days.

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

I am getting the result, but is there any way to skip Saturday and Sunday if they are in between these dates.

Vivek Maru
  • 8,347
  • 1
  • 24
  • 34

3 Answers3

0

See I Do this And Its Working Properly You Can Try This.

$day = date('l',strtotime($datte));
if($day == 'Saturday' || $day == 'Sunday')
{
 //SOME ACTION
}else{
  //SOME ACTION
}

Where L is Define Day Full Name.

0

I create an array with all the date numeric representation of the day (0-6 for sun-sat).
And if it's between 1-5 (mon-fri) add it in the array.
The count of the array is then the number of days without sat-sundays.

<?php

$startdate = '2017-08-04';

$datetime1 = new DateTime($startdate);
$datetime2 = new DateTime('2017-08-07');
$interval = $datetime1->diff($datetime2);
$days =  $interval->format('%a');

$arr =array();
for($i=0;$i<=$days;$i++){
    $day = date("w Y-m-d l", strtotime($startdate) + $i*86400); 
    if((int)$day[0] >= 1 && (int)$day[0] <= 5 ) $arr[] = $day;
}

var_dump($arr);

echo "days excluding sat-sundays " . count($arr);

https://3v4l.org/pPLpb

Edit added = to count the end date also.
Edit; there was something not working with my previous strtotime, it gave correct resultat but counted Tuesdays as Mondays.
Changed it to $i*86400 instead and added more data in the array for debugging.

Andreas
  • 23,610
  • 6
  • 30
  • 62
-1

holidayes hold saturday and sunday counts; w hold distance without holidays

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-12-13');
$interval = $datetime1->diff($datetime2);
$distance=$interval->format('%R%a');
$hoildays=($distance/7)*2;//  *2 cuz saturday and sunday
$W=$distance-($distance/$hoildays);
echo $W;
?>
  • This code does not work. It only assumes there is 2 sat-sundays per seven days. If the search is less than seven days or only wraps a weekend it fails. https://3v4l.org/VCpIk – Andreas Aug 02 '17 at 07:05