From e589c2d44aa77b168896f13233b35be098b0a403 Mon Sep 17 00:00:00 2001 From: vincent_loron Date: Fri, 5 Aug 2022 16:42:29 +0200 Subject: [PATCH] fix: add microseconds on getDateIntervalSpec() --- src/Carbon/CarbonInterval.php | 13 +++++++++---- tests/CarbonInterval/SpecTest.php | 6 ++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/Carbon/CarbonInterval.php b/src/Carbon/CarbonInterval.php index 5aca7422e7..592eaa7a41 100644 --- a/src/Carbon/CarbonInterval.php +++ b/src/Carbon/CarbonInterval.php @@ -2150,7 +2150,7 @@ public function divide($divider) * * @return string */ - public static function getDateIntervalSpec(DateInterval $interval) + public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false) { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), @@ -2158,10 +2158,15 @@ public static function getDateIntervalSpec(DateInterval $interval) static::PERIOD_DAYS => abs($interval->d), ]); + $seconds = abs($interval->s); + if ($microseconds && $interval->f > 0) { + $seconds = sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); + } + $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), - static::PERIOD_SECONDS => abs($interval->s), + static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; @@ -2185,9 +2190,9 @@ public static function getDateIntervalSpec(DateInterval $interval) * * @return string */ - public function spec() + public function spec(bool $microseconds = false) { - return static::getDateIntervalSpec($this); + return static::getDateIntervalSpec($this, $microseconds); } /** diff --git a/tests/CarbonInterval/SpecTest.php b/tests/CarbonInterval/SpecTest.php index 4978e00c3e..900f9fd373 100644 --- a/tests/CarbonInterval/SpecTest.php +++ b/tests/CarbonInterval/SpecTest.php @@ -73,6 +73,12 @@ public function testSecondInterval() $this->assertSame('PT1S', $ci->spec()); } + public function testMicrosecondsInterval() + { + $ci = new CarbonInterval(0, 0, 0, 0, 0, 0, 0, 12300); + $this->assertSame('PT0.012300S', $ci->spec(true)); + } + public function testMixedTimeInterval() { $ci = new CarbonInterval(0, 0, 0, 0, 1, 2, 3);