David
David

Reputation: 1191

PHP function to count business days adds a day to much

I have this PHP function:

function calculateNextDate($startDate, $days)
{
    $dateTime = new DateTime($startDate);

        while($days) {
            $dateTime->add(new DateInterval('P1D'));    

            if ($dateTime->format('N') < 6) {
                $days--;
            }
        }

    return $dateTime->format('Y-m-d');
}

It calculates what date it will be from a startdate given a number of days, and skips weekends.

If i echo this:

echo calculateNextDate('2012-10-01', '10');

It will print:

2012-10-15

Which is wrong... 2012-10-01 + 10 business days is 2012-10-12

Any idea on why it adds another day?

Upvotes: 0

Views: 95

Answers (1)

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

My kind sir, 1 + 10 = 11, not 10.

Therefore, if you ask to add 10 days to october 1st with your algorithm, it doesn't give the friday 12, it really gives out monday 15...

You want friday? Then it's 9 days...

Upvotes: 3

Related Questions