Skip to content

Commit

Permalink
Fix issue morilog#48 for subMonths method
Browse files Browse the repository at this point in the history
  • Loading branch information
Morteza Parvini committed Sep 23, 2018
1 parent e248032 commit dd0f80b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/Jalalian.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,28 @@ public function subMonths(int $months = 1): Jalalian
{
Assertion::greaterOrEqualThan($months, 1);

$years = (int)($months / 12);
$diff = ($this->getMonth() - $months);

if ($diff >= 1) {
$day = $this->getDay();
$targetMonthDays = $this->getDaysOf($diff);
$targetDay = $day <= $targetMonthDays ? $day : $targetMonthDays;

return new static(
$this->getYear(),
$diff,
$targetDay,
$this->getHour(),
$this->getMinute(),
$this->getSecond(),
$this->getTimezone()
);
}

$years = abs((int)($diff / 12));
$diff = abs($diff % 12) + 12;
$date = $years > 0 ? $this->subYears($years) : clone $this;

$diff = abs($this->getMonth() - $months + 12);


return $date->subYears(1)->addMonths($diff);
}

Expand Down Expand Up @@ -218,7 +235,7 @@ public function addMonths(int $months = 1): Jalalian
{
Assertion::greaterOrEqualThan($months, 1);

$years = (int)($months / 12);
$years = (int) ($months / 12);
$date = $years > 0 ? $this->addYears($years) : clone $this;

$months = ($months % 12) + $date->getMonth();
Expand All @@ -232,7 +249,6 @@ public function addMonths(int $months = 1): Jalalian
}
}


return $date->addDays($days);
}

Expand Down
10 changes: 10 additions & 0 deletions tests/JalalianTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,15 @@ public function testModifiers()
$this->assertEquals($jDate->subYears(10)->toString(), (new Jalalian(1387, 1, 31))->toString());
$this->assertTrue($jDate->subYears(2)->subMonths(34)->equalsTo(new Jalalian(1393, 10, 30)));

$jDate = (new Jalalian(1397, 6, 11))->subMonths(1);
$this->assertEquals($jDate->getMonth(), 5);

$this->assertEquals((new Jalalian(1397, 7, 1))->subMonths(1)->getMonth(), 6);

$jDate = Jalalian::now();
$month = $jDate->getMonth();
if ($month > 1) {
$this->assertEquals($month - 1, $jDate->subMonths()->getMonth());
}
}
}

0 comments on commit dd0f80b

Please sign in to comment.