Skip to content
Advertisement

PHP: Adding months to a date, while not exceeding the last day of the month

Looking to create a function that will do this in PHP.

I need to add a number of months to a date, but not exceed the last day of the month in doing so.

For example:

JavaScript

If I use date addition in PHP, I get overruns:

JavaScript

My specification doesn’t allow me to overrun into a new month.

What’s the easiest method to accomplish this?

Advertisement

Answer

You can compare the day of the month before and after you add 1 month. If it’s not the same, you exceeded the next month.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement