mnowotka
mnowotka

Reputation: 17238

PHP - total number of days is not an integer

The accepted answer in this question: Calculate business days is buggy. Just check

echo getWorkingDays("2012-01-01","2012-05-01",$holidays);

The problem is with this fragment:

$days = ($endDate - $startDate) / 86400 + 1;

So the minimal not working example is:

Why this expression:

($endDate - $startDate) / (60*60*24);

Is not an integer for:

 $startDate = strtotime("2012-01-01");
 $endDate = strtotime("2012-05-01");

Upvotes: 0

Views: 382

Answers (2)

jag2911
jag2911

Reputation: 1

As Ignacio says, it's because of passing the start (last Sunday of March) or end (last Sunday od October) of Daylight Saving Time... so you end up losing/gaining an hour and thus messing up the calculation.

All I added was round() to the equation and it deals with the situation perfectly :)

$days = round( (strtotime($endDate) - strtotime($startDate)) / 86400 + 1);

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799110

You've crossed a DST threshold. Whenever you do so your duration will be (usually) one hour shorter or longer. If you wish to avoid this then work exclusively with UTC.

Upvotes: 3

Related Questions