3

Today is 31st May

$currentM = date('m');
// 05

$nextM = date('m', strtotime('+1 month'));
// 07

What am I doing wrong? I don't understand why the next month is giving 07.

imulsion
  • 8,820
  • 20
  • 54
  • 84
l2aelba
  • 21,591
  • 22
  • 102
  • 138

4 Answers4

11

The next month from today (31/5) is the 31/6 which doesn't exist, so it forwards to the 1/7.

You may want to increment the actual month: $nextM = date('m') % 12 + 1

bwoebi
  • 23,637
  • 5
  • 58
  • 79
3

try :

$d = new DateTime();
$d->modify('first day of next month');
echo $d->format('m');
nl-x
  • 11,762
  • 7
  • 33
  • 61
1

You can use any of the following snippets,

$month = date('n') % 12 + 1;

(OR)

$month = date('m', strtotime('+1 months'));

(OR)

$month = date('m') + 1
khellang
  • 17,550
  • 6
  • 64
  • 84
Vinoth Babu
  • 6,724
  • 10
  • 36
  • 55
1

The problem is that today is the 31st. Adding a month may overlap 2 months.

I usually simply solve this by using day 1 to add a month and using day 28 to substract a month:

 echo(date('m'));
 echo "\n";
 echo(date('m', strtotime(date('Y-m-28') . ' -1 month'))); // day 28 - 1 month
 echo "\n";
 echo(date('m', strtotime(date('Y-m-1') . ' +1 month'))); // day 1 + 1 month

Output:

05
04
06
NLZ
  • 935
  • 6
  • 12