-1

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.

Computable
  • 976
  • 2
  • 4
  • 16
  • 2
    Consider https://carbon.nesbot.com/docs/, which is widely used and has things like `startOfMonth()` implemented. – ceejayoz Jan 31 '23 at 01:27
  • 2
    You should first very strictly define what you mean by "a month" and what moving a date forward by that interval _means_ with regard to your intended implementation and/or business case. ISO8601's `P1M` is one very specific case of "a month" that evidently does not fit your needs/expectations. – Sammitch Jan 31 '23 at 01:38
  • Do check this answer: https://stackoverflow.com/a/13422716/7224159 – Valentino Pereira Jan 31 '23 at 08:29
  • Does this answer your question? [How to get the next month in PHP](https://stackoverflow.com/questions/41952314/how-to-get-the-next-month-in-php) – jspit Jan 31 '23 at 12:28

1 Answers1

-1

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.

Computable
  • 976
  • 2
  • 4
  • 16