-
-
Save alexsandro-xpt/3797764 to your computer and use it in GitHub Desktop.
Algorítimo idiota (e caro) para cálculo de dias úteis entre duas datas.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Gets the business days between two dates. | |
* @param string $startDate ISO 8601 date string for start date. | |
* @param string $endDate ISO 8601 date string for end date. | |
* @param array $dayOffs List with day offs dates in ISO 8601. | |
* @return array The business days between two dates. | |
*/ | |
function businessDays($startDate, $endDate, array $dayOffs = array()) { | |
$startTime = strtotime($startDate); | |
$endTime = strtotime($endDate); | |
$businessDays = array(); | |
for ($currentTime = $startTime; $currentTime <= $endTime; $currentTime += 86400) { | |
$dayOfWeek = date('N', $currentTime); | |
if ($dayOfWeek < 6) { | |
$currentDay = date('Y-m-d', $currentTime); | |
$businessDays[] = $currentDay; | |
} | |
} | |
return array_diff($businessDays, $dayOffs); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'PHPUnit/Framework/TestCase.php'; | |
require_once 'businessDays.php'; | |
/** | |
* businessDays() test case. | |
*/ | |
class BusinessDaysTest extends PHPUnit_Framework_TestCase { | |
protected function setUp() { | |
parent::setUp(); | |
date_default_timezone_set('America/Sao_Paulo'); | |
} | |
public function dayOffProvider() { | |
return array(array( | |
array('2012-01-01', | |
'2012-04-06', | |
'2012-04-08', | |
'2012-04-21', | |
'2012-05-01', | |
'2012-09-07', | |
'2012-10-12', | |
'2012-11-02', | |
'2012-11-15', | |
'2012-12-25') | |
)); | |
} | |
public function testFullWeek() { | |
$this->assertCount(5, businessDays('2012-08-26', '2012-09-01')); | |
} | |
public function testWeekend() { | |
$this->assertEmpty(businessDays('2012-09-01', '2012-09-02')); | |
} | |
/** | |
* @dataProvider dayOffProvider | |
*/ | |
public function testDayOffNotIncluded(array $dayOffs) { | |
$this->assertNotContains('2012-09-07', businessDays('2012-09-02', '2012-09-08', $dayOffs)); | |
} | |
/** | |
* @dataProvider dayOffProvider | |
*/ | |
public function testWeekWithDayOff(array $dayOffs) { | |
$this->assertCount(4, businessDays('2012-09-02', '2012-09-08', $dayOffs)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment