Skip to content

Commit

Permalink
Add LocalDateRange::toPeriod()
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorel committed Jun 5, 2022
1 parent fd18a65 commit 213a4ba
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/LocalDateRange.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,16 @@ public function withEnd(LocalDate $end): LocalDateRange
return LocalDateRange::of($this->start, $end);
}

/**
* Returns the Period between the start date and end date.
*
* See `Period::between()` for how this is calculated.
*/
public function toPeriod(): Period
{
return Period::between($this->start, $this->end);
}

/**
* Returns an iterator for all the dates contained in this range.
*
Expand Down
38 changes: 38 additions & 0 deletions tests/LocalDateRangeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -356,4 +356,42 @@ public function providerWithEnd(): array
['2021-06-15/2021-07-07', '2021-07-08', '2021-06-15/2021-07-08'],
];
}

/**
* @dataProvider providerToPeriod
*/
public function testToPeriod(string $dateRange, string $expectedPeriod): void
{
$dateRange = LocalDateRange::parse($dateRange);

$this->assertSame($expectedPeriod, (string) $dateRange->toPeriod());
}

public function providerToPeriod(): array
{
return [
['2020-01-28/2020-03-01', 'P1M2D'],
['2020-01-29/2029-03-01', 'P9Y1M1D'],
['2020-01-29/2030-03-01', 'P10Y1M1D'],
['2020-01-28/2029-03-01', 'P9Y1M1D'],
['2020-01-28/2030-03-01', 'P10Y1M1D'],
['2020-02-28/2020-04-01', 'P1M4D'],
['2020-02-29/2020-04-01', 'P1M3D'],
['2020-03-01/2020-04-01', 'P1M'],
['2020-03-02/2020-04-01', 'P30D'],
['2021-01-01/2021-01-01', 'P0D'],
['2021-01-28/2021-03-01', 'P1M1D'],
['2021-02-28/2021-04-01', 'P1M4D'],
['2021-02-28/2021-04-01', 'P1M4D'],
['2021-03-01/2021-04-01', 'P1M'],
['2021-03-02/2021-04-01', 'P30D'],
['2021-02-28/2022-04-01', 'P1Y1M4D'],
['2021-03-01/2022-04-01', 'P1Y1M'],
['2021-03-02/2022-04-01', 'P1Y30D'],
['2021-03-03/2022-04-01', 'P1Y29D'],
['2021-03-30/2022-04-01', 'P1Y2D'],
['2021-03-31/2022-04-01', 'P1Y1D'],
['2021-04-01/2022-04-01', 'P1Y'],
];
}
}

0 comments on commit 213a4ba

Please sign in to comment.