Forum Moderators: coopster

Message Too Old, No Replies

Net Workday Function in PHP

to calculate the amount of working days in a given period

         

dainstructor

7:40 pm on Jan 3, 2007 (gmt 0)

10+ Year Member



Does anyone know of any good workday funtions that may be available in PHP? I'm not really sure if this exists, but I am thinking of a function similar to microsoft excel's NetWorkday function where I can pass it a period of time and reference a list of holidays, and it would return the amount of working day.

Thanks in advance guys.

whoisgregg

9:30 pm on Jan 3, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I just finished up a big work day calculator project a few weeks ago. I took that code and simplified it a bit (removing all the specific details for my needs and making it more user friendly for others to use). I hope this is what you had in mind. :)

Code should be mostly self explanatory. Define holiday dates inside the function and what days of the work week are valid work days. In my much bulkier solution I have a function that populates the holiday array with like three years worth of holiday dates and just call it with a

global $holidays;
instead of hard coding values into the function. I see you want to pass it an array of holidays which should also be a simple modification.

I found it was easiest to input a string date like '2007-01-13' so I wrote the function that way. I can imagine a desire for it to accept a timestamp but it should be easy to modify if that's important. It returns a timestamp by default, but you can also provide it the same string that date() [php.net] expects in the fourth parameter like "Y-m-d."

function workingDays($days=5,$start=null,$skipToday=null,$returnFormat=null){
// populate this with an array of work dates
$holidays = array('2007-01-08','2007-12-25','2007-12-31');
// valid work days, 0 = sunday, 6 = saturday
$workDays = array('1', '2', '3', '4', '5');
$start = (isset($start))? date("Y-m-d",strtotime($start)) : date("Y-m-d");
$daysGoal = (isset($days) && intval($days)==$days)? $days : 5;
$dayCounter = 0;
if(isset($skipToday) && $skipToday===true){
$dayCounter = 1;
}
$daysSoFar = 0;
while( $daysSoFar < $daysGoal ){
$workingDate = strtotime("+$dayCounter days", strtotime("$start 12:00:00"));
if( in_array(date("w",$workingDate),$workDays) ){
if(!(in_array(date("Y-m-d", $workingDate), $holidays))){
$daysSoFar++;
}
}
$dayCounter++;
}
if(isset($returnFormat)){
return date($returnFormat,$workingDate);
} else {
return $workingDate;
}
}

[edited by: whoisgregg - Wed, 03 Jan 2007 21:31:05 GMT]
Oh yeah, also define default values for workdays if you tend to call it with the same values.

dainstructor

9:38 pm on Jan 3, 2007 (gmt 0)

10+ Year Member



Wow. Thanks Whoisgregg! I'm a little new to PHP so it may take me a while to completely incorporate this function. It looks pretty straight forward however.

Thanks again!
Cheers.