diff --git a/src/Period.php b/src/Period.php index ac358058..10fae4f6 100644 --- a/src/Period.php +++ b/src/Period.php @@ -143,7 +143,12 @@ public static function __set_state(array $period) */ public static function createFromDay($day) { - $startDate = static::filterDatePoint($day)->setTime(0, 0, 0); + $startDate = static::filterDatePoint($day); + $startDate = $startDate->createFromFormat( + static::DATE_LOCALE, + $startDate->format('Y-m-d').' 00:00:00.000000', + $startDate->getTimeZone() + ); return new static($startDate, $startDate->add(new DateInterval('P1D'))); } @@ -821,14 +826,21 @@ public function split($interval) */ public function intersect(Period $period) { - if ($this->abuts($period)) { - throw new LogicException('Both object should not abuts'); + if (! $this->overlaps($period)) { + throw new LogicException('Both Period objects must overlaps'); } - return new static( - ($period->getStartDate() > $this->startDate) ? $period->getStartDate() : $this->startDate, - ($period->getEndDate() < $this->endDate) ? $period->getEndDate() : $this->endDate - ); + $startDate = $period->getStartDate(); + if ($startDate < $this->startDate) { + $startDate = $this->startDate; + } + + $endDate = $period->getEndDate(); + if ($endDate > $this->endDate) { + $endDate = $this->endDate; + } + + return new static($startDate, $endDate); } /** diff --git a/test/PeriodTest.php b/test/PeriodTest.php index 327ff703..cc671287 100644 --- a/test/PeriodTest.php +++ b/test/PeriodTest.php @@ -10,6 +10,20 @@ use League\Period\Period; use PHPUnit_Framework_TestCase as TestCase; +class ExtendedDate extends DateTimeImmutable +{ + public static function createFromFormat($format, $time, $timezone = null) + { + if (!is_object($timezone) || !$timezone instanceof DateTimeZone) { + $timezone = date_default_timezone_get(); + } + + $datetime = parent::createFromFormat($format, $time, $timezone); + + return new self($datetime->format('Y-m-d H:i:s.u'), $timezone); + } +} + class PeriodTest extends TestCase { private $timezone; @@ -394,6 +408,21 @@ public function testCreateFromDay() $this->assertEquals($period->getEndDate(), new DateTimeImmutable('2015-01-04')); } + public function testCreateFromDayPreserveTimezone() + { + $period = Period::createFromDay('2008-07-01T22:35:17+08:00'); + $this->assertEquals('+08:00', $period->getStartDate()->format('P')); + $this->assertEquals('+08:00', $period->getEndDate()->format('P')); + } + + public function testCreateFromDayPreserveInstance() + { + $today = new ExtendedDate('NOW'); + $period = Period::createFromDay($today); + $this->assertInstanceof(ExtendedDate::class, $period->getStartDate()); + $this->assertInstanceof(ExtendedDate::class, $period->getEndDate()); + } + public function testIsBeforeDatetime() { $orig = Period::createFromDuration('2012-01-01', '1 MONTH');