Date plus one month php

I have a little date problem in PHP.

When I made January 31 + 1 with this code

$newDate = date('Ym-d', strtotime('31-01-2016'.' + 1 month')); echo $newDate; 

it gives me March 2, but I need to give me February 29,

I need to add 1 month and not 30 days.

ditto for all dates: e.g. January 01 + 1 month => February 1

January 29 + 1 month => February 29

January 30 + 1 month => February 29

January 31 + 1 month => February 29

thanks for the help

+6
source share
4 answers

I think you are looking for this type of date.

 <?php $date = date('2016-01-31'); $currentMonth = date("m",strtotime($date)); $nextMonth = date("m",strtotime($date."+1 month")); if($currentMonth==$nextMonth-1){ $nextDate = date('Ym-d',strtotime($date." +1 month")); }else{ $nextDate = date('Ym-d', strtotime("last day of next month",strtotime($date))); } echo "Next date would be : $nextDate"; ?> 

Check out the demo version: https://eval.in/610034

  • If the date is 31-01-2016 , the next date will be 29-02-2016
  • If the date is 25-01-2016 , the next date will be 25-02-2016
+5
source

Just try:

 $date = new DateTime('2016-01-31'); $date->modify('last day of next month'); 

This, of course, only counts if you always go from the end of one mole to the end of the next.

+3
source

try it,

 $date = "2016-01-29"; $date = date('Ym-d', strtotime("last day of next month",strtotime($date))); echo $date; 

https://3v4l.org/Y9PpV

+1
source

How about something like this:

 date_default_timezone_set('UTC'); $current_month = (int) date('m'); $year = date('y'); $newDate = date('Ym-d', strtotime('31-1-2016'.' + 1 month')); if($current_month == 12) { $new_month=0; $year++; } $d = new DateTime( $year.'-'.($current_month+1).'-01' ); echo $d->format( 'Ymt' )."\n"; 

Change $ current_month / $ year based on your needs ......

0
source

All Articles