From 8c4c11346b4fcc8df1c00a1e1290813f9e623376 Mon Sep 17 00:00:00 2001 From: Adrien Crivelli Date: Sun, 2 Oct 2016 14:46:11 +0900 Subject: [PATCH] Fix unit tests for DATEDIF() Leap years where not properly taken into consideration --- src/PhpSpreadsheet/Calculation/DateTime.php | 19 +++++++++--- .../Calculation/DateTimeTest.php | 3 -- tests/data/Calculation/DateTime/DATEDIF.php | 30 +++++++++++++++++++ 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/src/PhpSpreadsheet/Calculation/DateTime.php b/src/PhpSpreadsheet/Calculation/DateTime.php index a748c4eb..5d9614a1 100644 --- a/src/PhpSpreadsheet/Calculation/DateTime.php +++ b/src/PhpSpreadsheet/Calculation/DateTime.php @@ -729,13 +729,24 @@ class DateTime case 'YD': $retVal = intval($difference); if ($endYears > $startYears) { - while ($endYears > $startYears) { + $isLeapStartYear = $PHPStartDateObject->format('L'); + $wasLeapEndYear = $PHPEndDateObject->format('L'); + + // Adjust end year to be as close as possible as start year + while ($PHPEndDateObject >= $PHPStartDateObject) { $PHPEndDateObject->modify('-1 year'); $endYears = $PHPEndDateObject->format('Y'); } - $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z'); - if ($retVal < 0) { - $retVal += 365; + $PHPEndDateObject->modify('+1 year'); + + // Get the result + $retVal = $PHPEndDateObject->diff($PHPStartDateObject)->days; + + // Adjust for leap years cases + $isLeapEndYear = $PHPEndDateObject->format('L'); + $limit = new \DateTime($PHPEndDateObject->format('Y-02-29')); + if (!$isLeapStartYear && !$wasLeapEndYear && $isLeapEndYear && $PHPEndDateObject >= $limit ) { + $retVal--; } } break; diff --git a/tests/PhpSpreadsheetTests/Calculation/DateTimeTest.php b/tests/PhpSpreadsheetTests/Calculation/DateTimeTest.php index bc25d58d..6abd435c 100644 --- a/tests/PhpSpreadsheetTests/Calculation/DateTimeTest.php +++ b/tests/PhpSpreadsheetTests/Calculation/DateTimeTest.php @@ -416,12 +416,9 @@ class DateTimeTest extends \PHPUnit_Framework_TestCase /** * @dataProvider providerDATEDIF - * @group fail19 */ public function testDATEDIF() { - $this->markTestIncomplete('TODO: This test should be fixed'); - $args = func_get_args(); $expectedResult = array_pop($args); $result = call_user_func_array([DateTime::class, 'DATEDIF'], $args); diff --git a/tests/data/Calculation/DateTime/DATEDIF.php b/tests/data/Calculation/DateTime/DATEDIF.php index 106385fc..e8776c0f 100644 --- a/tests/data/Calculation/DateTime/DATEDIF.php +++ b/tests/data/Calculation/DateTime/DATEDIF.php @@ -1,6 +1,36 @@