Oihana PHP

addMonths.php

Table of Contents

Functions

addMonths()  : DateTimeImmutable
Returns a copy of a date shifted by a number of months, clamping day overflow.

Functions

addMonths()

Returns a copy of a date shifted by a number of months, clamping day overflow.

addMonths(DateTimeInterface $date, int $months) : DateTimeImmutable

A new DateTimeImmutable is returned ; the source date is never modified. The wall-clock time of day is preserved.

Unlike DateTimeImmutable::modify( '+1 month' ), which overflows into the following month when the source day does not exist in the target month (2026-01-31 + 1 month natively lands on 2026-03-03, February having only 28 days), this function clamps the day to the last day of the target month (2026-02-28). This is the behaviour of every mainstream date library ; the raw, overflowing behaviour stays one ->modify( '+1 month' ) call away when it is genuinely what is wanted.

Parameters
$date : DateTimeInterface

The source date.

$months : int

The number of months to add (negative to subtract).

Tags
example
use function oihana\core\date\addMonths;

addMonths( new DateTimeImmutable( '2026-01-15' ) , 1 )  ; // 2026-02-15
addMonths( new DateTimeImmutable( '2026-01-31' ) , 1 )  ; // 2026-02-28 (clamped, not 2026-03-03)
addMonths( new DateTimeImmutable( '2024-01-31' ) , 1 )  ; // 2024-02-29 (leap year)
addMonths( new DateTimeImmutable( '2026-03-31' ) , -1 ) ; // 2026-02-28 (clamped)
author

Marc Alcaraz (ekameleon)

since
1.2.0
Return values
DateTimeImmutable

A new immutable date shifted by $months months, day-clamped.

On this page

Search results