Unexpected Results When Adding Months To a Date

When adding or subtracting months to a date in PHP, you’ll get some uninuitive results in some cases. For example, strtotime( ‘+1 month’ ) will return the timestamp for July 1st when it’s executed on May 31st, instead of the expected June 30th. This is because a “month” is a fuzzy metric (i.e., some months have more or fewer days than others) and because there is no June 31st, PHP adds the extra day and comes up with July 1st.

The solution is to instead query for the first day of the next month. In PHP 5.3+ you can use some of the new¬†relative formats like, strtotime( ‘first day of next month’ ), or on older systems you can use mktime().

For a more detailed explanation, see Derick Rethan’s article on the topic.

Leave a Reply

Your email address will not be published. Required fields are marked *