# Odd date calculation

## Recommended Posts

Hi.  I am writing software to choose employees for drug testing.  Originally it was choosing 5 per day, Mon-Thu.  No problem there, that's easy.  Now, they want to ensure everyone gets tested each calendar year.  So now I need the program to look at the date and calculate the days between now and 12/31 then divide the people that haven't been tested by days to get number per day that need testing so it gets all done by the end of the year.

The snag I hit is how to calculate it.  I can easily get days to 12/31, but I need to drop the Fridays, Saturdays and Sundays of each week.  That has me a little perplexed.  Is there a way to make that kind of calculation?  Thanks!

##### Share on other sites

I found some code while Googling:

```\$workdays = explode(",", "1,1,1,1,0,0,0"); // turn string to array (Monday to Sunday)
\$days = 0;
\$time = strtotime("2014-06-01");
\$end_time = strtotime("2014-06-30");
while (\$time < \$end_time) {
\$day_of_week = date("N", \$time) - 1; // 0 = Monday, 6 = Sunday
if (\$workdays[\$day_of_week] == 1) {
\$days++;
}
\$time = strtotime("+1 day", \$time); // add one day to time
}
echo \$days;
```

##### Share on other sites

Odd, it cut off my text after the code.  Anyway, it works fine for months that have whole, unbroken weeks.  Like this month, June 14.  16 days matching my criteria (Mon-Thu).  However, if I try it with a month like July where the first is on Tuesday and the thirty-first is on Thursday, there are 19 days but the code returns 18.  In September, there are 18 days  but the code returns 17.  I could add \$days++, but for unbroken months it will be wrong and I'm not sure how to programatically tell that a month is broken up or not.  Then again, it's after midnight so maybe I should try tomorrow when I am not sleepy

##### Share on other sites

How about getting the number of days until the end of the year instead of looking at months? Then do some arithmetic.

Edited by boompa

##### Share on other sites

try

```\$dt1 = new DateTime('tomorrow');
\$dt2 = new DateTime('2015-01-01');
\$di = DateInterval::createFromDateString('next weekday');
\$dp = new DatePeriod(\$dt1, \$di, \$dt2);
\$count = 0;
foreach (\$dp as \$d) {
\$dt = \$d->format('D M j');
\$wd = \$d->format('w');
if (\$wd != 5) {  // not Friday
++\$count;
echo "\$dt<br>"; // optional
}
}
echo "<br>Total days - \$count";
```
• 1

## Create an account

Register a new account

×

• Chat