From bf14b0e87dc6174523c661b7de073fa952450d9f Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sat, 6 Feb 2021 00:39:27 +0330 Subject: [PATCH] bug fix add month algorithm and add a test to check it --- src/Traits/AdditionAndSubstraction.php | 16 ++++++++++------ tests/CalendarTest.php | 3 ++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/Traits/AdditionAndSubstraction.php b/src/Traits/AdditionAndSubstraction.php index c39d2b4..92fd7e0 100644 --- a/src/Traits/AdditionAndSubstraction.php +++ b/src/Traits/AdditionAndSubstraction.php @@ -11,7 +11,7 @@ public function addYear($count) $date = $this->currentCalendar->timestampToDate($this->timestamp + $this->timezoneOffset); $timestamp = $this->currentCalendar->dateToTimestamp($date->year + $count, $date->month, $date->day, $date->hour, $date->minute, $date->second); $this->timestamp = $timestamp - $this->timezoneOffset; - + return $this; } @@ -19,11 +19,15 @@ public function addMonth($count) { $date = $this->currentCalendar->timestampToDate($this->timestamp + $this->timezoneOffset); $totalMonth = $date->month + $count; - $year = $date->year + floor($totalMonth / 12); - $month = $totalMonth % 12; - $timestamp = $this->currentCalendar->dateToTimestamp($year, $month, $date->day, $date->hour, $date->minute, $date->second); + $year = $date->year + floor($totalMonth / 12) - (($totalMonth % 12) == 0 ? 1 : 0); + $month = ($totalMonth % 12) == 0 ? 12 : ($totalMonth % 12); + + $daysInMonth = $this->currentCalendar->daysInMonth($year, $month); + $day = $date->day <= $daysInMonth ? $date->day : $daysInMonth; + + $timestamp = $this->currentCalendar->dateToTimestamp($year, $month, $day, $date->hour, $date->minute, $date->second); $this->timestamp = $timestamp - $this->timezoneOffset; - + return $this; } @@ -107,7 +111,7 @@ public function subMinute($count) public function subSecond($count) { $this->timestamp = $this->timestamp - $count; - + return $this; } } \ No newline at end of file diff --git a/tests/CalendarTest.php b/tests/CalendarTest.php index 8511f7a..fa76d77 100644 --- a/tests/CalendarTest.php +++ b/tests/CalendarTest.php @@ -22,8 +22,9 @@ public function testJalaliDateTime() $this->assertTrue($pasoonate->jalali()->setDate(1399,12,11)->daysInMonth() === 30); $julianDayNumber = $pasoonate->jalali()->setDate(1399,12,11)->getJulianDayNumber(); - $this->assertTrue($pasoonate->jalali()->setJulianDayNumber($julianDayNumber)->gregorian()->getJulianDayNumber() == $julianDayNumber); + + $this->assertEquals($pasoonate->jalali()->setDate(1399,1,31)->addMonth(11)->format('yyyy/MM/dd'), '1399/12/30'); } public function testGregorianDateTime()