Home > Net >  Modify DateTime instance to next month
Modify DateTime instance to next month

Time:02-02

Given a DateTime instance initialized as :

$tgtDateDT = new DateTime('now');

which for example equates to 2023-01-30 when formatted as ->format("Y-m-d"),

I want to advance the month to February (for rendering a calendar) where I was hoping to do:

$nextMonth = $tgtDateDT->add(new DateInterval('P1M'));

Which when formatted with ->format("Y-m-d") yields

2023-03-02

So February has 28 days so I understand it may yield an unpredictable result.

So how can I take a date from any day in one month and advance it to say "the first" of the next month - preferably with DateInterval.

For my calendar rendering the new date can be any day in the next month.

CodePudding user response:

Given any day in a month and needing to advance to the first day of the next month (such as flipping to next month on a calendar) the following can be performed:

$tgtDateDT = new DateTime('now');
// implement "startOfMonth"
$tgtDateDT->setDate($tgtDateDT->format('Y'), $tgtDateDT->format('m'),1);
$tgtDateDT->add(new DateInterval('P1M'));
printf ($tgtDateDT);

So 2023-01-30 yields 2023-02-01.

  • Related