Aug
06
|
<?php
//get current month for example
$beginday=date(“Y-m-01”);
$lastday=date(“Y-m-t”);
$nr_work_days = getWorkingDays($beginday,$lastday);
echo $nr_work_days;
function getWorkingDays($startDate, $endDate){
$begin=strtotime($startDate);
$end=strtotime($endDate);
if($begin>$end){
echo “startdate is in the future! <br />”;
return 0;
}else{
$no_days=0;
$weekends=0;
while($begin<=$end){
$no_days++; // no of days in the given interval
$what_day=date(“N”,$begin);
if($what_day>5) { // 6 and 7 are weekend days
$weekends++;
};
$begin+=86400; // +1 day
};
$working_days=$no_days-$weekends;
return $working_days;
}
}
?>
April 26th, 2013 at 6:35 pm
Thanks a lot for the sharing, Mugurel.
The solution is the simplest and clearest one on the PHP world.
October 23rd, 2013 at 1:15 pm
Thanks for this, helped me to build my own (I’m adding in public holidays). But cant you just do:
if($what_day<=5) { // 6 and 7 are weekend days
$working_days++;
};
Rather than working which are weekends?
December 27th, 2013 at 8:52 pm
Technically, I think it is quicker to check for 6/7, because the ‘if’ only fires 2 out of 7 times instead of 5 out of 7 times. <-Behold the nit-pickiness 🙂
Jeff
January 3rd, 2014 at 4:34 pm
this actually works! 🙂
awesome!
thanks for the code snippet!
February 28th, 2014 at 7:52 am
Really great work, racked my brains until I came across this beauty. Thanks agian
February 28th, 2014 at 9:22 am
A loop? Haven’t you ever heard about primitive functions for calculating integrals?
July 15th, 2014 at 10:21 am
My two cents:
function workDaysBetweenDates(DateTime $date1, DateTime $date2)
{
$workdays = 0;
$differenceInDays = $date1->diff($date2)->d;
for ($i = 1; $i <= $differenceInDays; $i++) {
$dayOftheWeek = date('N', strtotime("+{$i} days"));
if ($dayOftheWeek <= 5) {
$add = 6 – $dayOftheWeek;
$workdays += $add;
$i += $add + 1;
}
}
return $workdays;
}
This only fires once a week unless the starting date is on a saturday, then it will fire two times for the first week.
February 7th, 2015 at 10:29 am
hey,
i have a table of company holidays with just two columns, date and occasion. I want to get the no. of working days keeping this table also in mind along with saturdays and sundays
please help me out
June 7th, 2016 at 3:02 pm
given top getWorkingDays working like charm.
i need one help.
i am passing array like public holidays list,
then exclude the public holiday then return the count of working days.
July 26th, 2017 at 9:52 pm
Thanks for the solution. life saver 😉
December 21st, 2017 at 4:33 pm
Thank you sooooo much sir. it’s very help full for me…