Skip to content

Commit

Permalink
Merge pull request #2651 from Nakatox/date-interval-spec-microseconds
Browse files Browse the repository at this point in the history
fix: add microseconds on getDateIntervalSpec()
  • Loading branch information
kylekatarnls authored Aug 6, 2022
2 parents fab32b8 + e589c2d commit bdf4f4f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/Carbon/CarbonInterval.php
Original file line number Diff line number Diff line change
Expand Up @@ -2150,18 +2150,23 @@ 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),
static::PERIOD_MONTHS => abs($interval->m),
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;
Expand All @@ -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);
}

/**
Expand Down
6 changes: 6 additions & 0 deletions tests/CarbonInterval/SpecTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit bdf4f4f

Please sign in to comment.