diff --git a/src/LocalDateRange.php b/src/LocalDateRange.php index a239ddd..5a30a28 100644 --- a/src/LocalDateRange.php +++ b/src/LocalDateRange.php @@ -228,6 +228,16 @@ public function count() : int return $this->end->toEpochDay() - $this->start->toEpochDay() + 1; } + /** + * Returns Duration of this range + * + * @return Duration + */ + public function toDuration(): Duration + { + return Duration::ofDays($this->count()); + } + /** * Serializes as a string using {@see LocalDateRange::__toString()}. */ diff --git a/src/YearMonthRange.php b/src/YearMonthRange.php index e082d39..4322fd7 100644 --- a/src/YearMonthRange.php +++ b/src/YearMonthRange.php @@ -174,6 +174,16 @@ public function toLocalDateRange(): LocalDateRange ); } + /** + * Returns Duration of this range + * + * @return Duration + */ + public function toDuration(): Duration + { + return $this->toLocalDateRange()->toDuration(); + } + /** * Serializes as a string using {@see YearMonthRange::__toString()}. */ diff --git a/tests/LocalDateRangeTest.php b/tests/LocalDateRangeTest.php index 64a39e0..0571d07 100644 --- a/tests/LocalDateRangeTest.php +++ b/tests/LocalDateRangeTest.php @@ -5,6 +5,7 @@ namespace Brick\DateTime\Tests; use Brick\DateTime\DateTimeException; +use Brick\DateTime\Duration; use Brick\DateTime\LocalDate; use Brick\DateTime\LocalDateRange; use Brick\DateTime\Parser\DateTimeParseException; @@ -172,6 +173,16 @@ public function testCount(string $range, int $count): void $this->assertCount($count, LocalDateRange::parse($range)); } + /** + * @dataProvider providerCount + */ + public function testToDuration(string $rangeString, int $expectedDaysCount): void + { + $expectedSeconds = $expectedDaysCount * 60 * 60 * 24; + $rangeObject = LocalDateRange::parse($rangeString); + $this->assertDurationIs($expectedSeconds, 0, $rangeObject->toDuration()); + } + public function providerCount() : array { return [ diff --git a/tests/YearMonthRangeTest.php b/tests/YearMonthRangeTest.php index 7b60402..6283799 100644 --- a/tests/YearMonthRangeTest.php +++ b/tests/YearMonthRangeTest.php @@ -198,6 +198,29 @@ public function providerToLocalDateRange(): array ]; } + /** + * @dataProvider providerToDuration + */ + public function testToDuration(string $range, int $expectedDaysCount): void + { + $actualDuration = YearMonthRange::parse($range)->toDuration(); + $expectedSeconds = $expectedDaysCount * 60 * 60 * 24; + $this->assertDurationIs($expectedSeconds, 0, $actualDuration); + } + + public function providerToDuration(): array + { + return [ + ['1900-01/1900-12', 365], + ['1900-05/1901-04', 365], + ['1904-01/1904-12', 366], + ['1900-02/1900-02', 28], + ['2000-01/2000-02', 31 + 29], + ['2001-01/2001-02', 31 + 28], + ['1901-01/3000-12', 401767], + ]; + } + public function testJsonSerialize(): void { $this->assertSame(json_encode('2008-12/2011-01'), json_encode(YearMonthRange::of(