diff --git a/src/Symfony/Component/Clock/CHANGELOG.md b/src/Symfony/Component/Clock/CHANGELOG.md index 3b13157397f0f..764accf07df42 100644 --- a/src/Symfony/Component/Clock/CHANGELOG.md +++ b/src/Symfony/Component/Clock/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +7.1 +--- + + * Add `DatePoint::get/setMicroseconds()` + 6.4 --- diff --git a/src/Symfony/Component/Clock/DatePoint.php b/src/Symfony/Component/Clock/DatePoint.php index 5d8ace6374bc8..7128c8f0ed0fc 100644 --- a/src/Symfony/Component/Clock/DatePoint.php +++ b/src/Symfony/Component/Clock/DatePoint.php @@ -117,4 +117,26 @@ public function getTimezone(): \DateTimeZone { return parent::getTimezone() ?: throw new \DateInvalidTimeZoneException('The DatePoint object has no timezone.'); } + + public function setMicroseconds(int $microseconds): static + { + if ($microseconds < 0 || $microseconds > 999999) { + throw new \DateRangeError('DatePoint::setMicroseconds(): Argument #1 ($microseconds) must be between 0 and 999999, '.$microseconds.' given'); + } + + if (\PHP_VERSION_ID < 80400) { + return $this->setTime(...explode('.', $this->format('H.i.s.'.$microseconds))); + } + + return parent::setMicroseconds($microseconds); + } + + public function getMicroseconds(): int + { + if (\PHP_VERSION_ID >= 80400) { + return parent::getMicroseconds(); + } + + return $this->format('u'); + } } diff --git a/src/Symfony/Component/Clock/Tests/DatePointTest.php b/src/Symfony/Component/Clock/Tests/DatePointTest.php index c9d7ddf10a803..7dbb30c9b5730 100644 --- a/src/Symfony/Component/Clock/Tests/DatePointTest.php +++ b/src/Symfony/Component/Clock/Tests/DatePointTest.php @@ -57,4 +57,20 @@ public function testModify() $this->expectExceptionMessage('Failed to parse time string (Bad Date)'); $date->modify('Bad Date'); } + + public function testMicroseconds() + { + $date = new DatePoint('2010-01-28 15:00:00.123456'); + + $this->assertSame('2010-01-28 15:00:00.123456', $date->format('Y-m-d H:i:s.u')); + + $date = $date->setMicroseconds(789); + + $this->assertSame('2010-01-28 15:00:00.000789', $date->format('Y-m-d H:i:s.u')); + $this->assertSame(789, $date->getMicroseconds()); + + $this->expectException(\DateRangeError::class); + $this->expectExceptionMessage('DatePoint::setMicroseconds(): Argument #1 ($microseconds) must be between 0 and 999999, 1000000 given'); + $date->setMicroseconds(1000000); + } }