Skip to content

Commit

Permalink
#1456 Fix negative unit interval construction
Browse files Browse the repository at this point in the history
  • Loading branch information
kylekatarnls committed Oct 9, 2018
1 parent 1dbd3cb commit daecfe2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/Carbon/CarbonInterval.php
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,11 @@ public static function instance(DateInterval $di)
{
$instance = new static(static::getDateIntervalSpec($di));
$instance->invert = $di->invert;
foreach (array('y', 'm', 'd', 'h', 'i', 's') as $unit) {
if ($di->$unit < 0) {
$instance->$unit *= -1;
}
}

return $instance;
}
Expand Down Expand Up @@ -961,15 +966,15 @@ public function times($factor)
public static function getDateIntervalSpec(DateInterval $interval)
{
$date = array_filter(array(
static::PERIOD_YEARS => $interval->y,
static::PERIOD_MONTHS => $interval->m,
static::PERIOD_DAYS => $interval->d,
static::PERIOD_YEARS => abs($interval->y),
static::PERIOD_MONTHS => abs($interval->m),
static::PERIOD_DAYS => abs($interval->d),
));

$time = array_filter(array(
static::PERIOD_HOURS => $interval->h,
static::PERIOD_MINUTES => $interval->i,
static::PERIOD_SECONDS => $interval->s,
static::PERIOD_HOURS => abs($interval->h),
static::PERIOD_MINUTES => abs($interval->i),
static::PERIOD_SECONDS => abs($interval->s),
));

$specString = static::PERIOD_PREFIX;
Expand Down
8 changes: 8 additions & 0 deletions tests/CarbonInterval/ConstructTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,4 +267,12 @@ public function testCallInvalidStaticMethod()
{
$this->assertNull(CarbonInterval::anything());
}

public function testNegativeHour()
{
$before = new Carbon('2018-10-08 14:53:00');
$after = new Carbon('2018-11-15 14:00:00');

$this->assertCarbonInterval($after->diffAsCarbonInterval($before, false), 0, 1, 7, -1, 7, 0);
}
}

0 comments on commit daecfe2

Please sign in to comment.