Skip to content

Commit 18fcfb8

Browse files
feat: [I18n\Time] addCalendarMonths()
1 parent 115d37e commit 18fcfb8

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

system/I18n/TimeTrait.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,29 @@ public function addMonths(int $months)
749749
return $time->add(DateInterval::createFromDateString("{$months} months"));
750750
}
751751

752+
/**
753+
* Returns a new Time instance with $months calendar months added to the time.
754+
*/
755+
public function addCalendarMonths(int $months): Time
756+
{
757+
$time = clone $this;
758+
759+
$year = (int) $time->getYear();
760+
$month = (int) $time->getMonth() + $months;
761+
$day = (int) $time->getDay();
762+
763+
// Adjust year and month for overflow
764+
$year += intdiv($month - 1, 12);
765+
$month = (($month - 1) % 12) + 1;
766+
767+
// Find the last valid day of the target month
768+
$lastDayOfMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
769+
$correctedDay = min($day, $lastDayOfMonth);
770+
771+
// Return new time instance
772+
return static::create($year, $month, $correctedDay, (int) $this->getHour(), (int) $this->getMinute(), (int) $this->getSecond(), $this->getTimezone(), $this->locale);
773+
}
774+
752775
/**
753776
* Returns a new Time instance with $years added to the time.
754777
*

0 commit comments

Comments
 (0)