Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP add month to date on a date with day of month 31

I'm using code that works fine on all dates, except 2015-05-31. The code brings me the first day of next month. it works on every date, even if day of month is 31.

$time = strtotime('2015-07-31');
$final = date("Y-m-1", strtotime("+1 month", $time));
echo $final;

output will be --> 2015-08-1.

For some reason on the date 2015-05-31 it returns 2015-07-1 instead of 2015-06-01

$time = strtotime('2015-05-31');
$final = date("Y-m-1", strtotime("+1 month", $time));
echo $final;

Its probably because 6-2014 has 30 days, and 8-2014 has 31 days, so +1 month adds 30 days and not a "month".

How could i get correctly the first day of next month on every date?

Thank you.

like image 957
BenB Avatar asked Jan 31 '26 06:01

BenB


1 Answers

I think this should work -

$time = strtotime("2015-05-31");
echo $final = date("Y-m-d", strtotime("first day of next month", $time));
like image 120
TBI Avatar answered Feb 02 '26 21:02

TBI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!