From 4b22406f4f7dc58b2a8fa0f7c9e5c8b5bd8413ba Mon Sep 17 00:00:00 2001 From: Alexey Solodkiy Date: Sat, 30 Sep 2023 19:12:08 +0300 Subject: [PATCH] LocalDateRange::toInterval --- src/LocalDateRange.php | 19 +++++++++++++++++++ tests/LocalDateRangeTest.php | 23 +++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/LocalDateRange.php b/src/LocalDateRange.php index 58ca387..a7ed588 100644 --- a/src/LocalDateRange.php +++ b/src/LocalDateRange.php @@ -244,6 +244,25 @@ public function jsonSerialize(): string return (string) $this; } + /** + * Converts this LocalDateRange to Interval instance. + * + * The result is Interval from 00:00 start date and 00:00 end date + one day (because end in Interval is exclude) + * in the given time-zone. + */ + public function toInterval(TimeZone $timeZone): Interval + { + $startZonedDateTime = $this->getStart() + ->atTime(LocalTime::min()) + ->atTimeZone($timeZone); + $endZonedDateTime = $this->getEnd() + ->plusDays(1) + ->atTime(LocalTime::min()) + ->atTimeZone($timeZone); + + return $startZonedDateTime->getIntervalTo($endZonedDateTime); + } + /** * Converts this LocalDateRange to a native DatePeriod object. * diff --git a/tests/LocalDateRangeTest.php b/tests/LocalDateRangeTest.php index 0bb6421..a6f1839 100644 --- a/tests/LocalDateRangeTest.php +++ b/tests/LocalDateRangeTest.php @@ -8,6 +8,7 @@ use Brick\DateTime\LocalDate; use Brick\DateTime\LocalDateRange; use Brick\DateTime\Parser\DateTimeParseException; +use Brick\DateTime\TimeZone; use function array_map; use function iterator_count; @@ -240,6 +241,28 @@ public function providerToNativeDatePeriod(): array ]; } + /** + * @dataProvider providerToInterval + */ + public function testToInterval(string $range, string $timeZone, string $expectedInterval): void + { + $actualResult = LocalDateRange::parse($range)->toInterval(TimeZone::parse($timeZone)); + self::assertSame($expectedInterval, (string) $actualResult); + } + + public function providerToInterval(): array + { + return [ + ['2010-01-01/2010-01-01', 'UTC', '2010-01-01T00:00Z/2010-01-02T00:00Z'], + ['2010-01-01/2020-12-31', 'UTC', '2010-01-01T00:00Z/2021-01-01T00:00Z'], + ['2022-03-20/2022-03-26', 'Europe/London', '2022-03-20T00:00Z/2022-03-27T00:00Z'], + ['2022-03-20/2022-03-27', 'Europe/London', '2022-03-20T00:00Z/2022-03-27T23:00Z'], + ['2022-03-20/2022-03-26', 'Europe/Berlin', '2022-03-19T23:00Z/2022-03-26T23:00Z'], + ['2022-03-20/2022-03-27', 'Europe/Berlin', '2022-03-19T23:00Z/2022-03-27T22:00Z'], + ['2022-01-01/2022-12-31', 'Europe/Berlin', '2021-12-31T23:00Z/2022-12-31T23:00Z'], + ]; + } + /** * @dataProvider providerIntersectsWith */