PHP – Get the next month by strtotime

I am working on a Hotel Booking website. The booking feature is provided by Hotel Booking System for Ubercart. But this module is not actively maintained so there are some bugs which i have to fix it for myself.

One of the bug is about strtotime(‘+1 month’). Intuitively, you may think you could get a date of next month. But here comes the problem. Assume you are now on 31st Jan. Since February only has 28 days (sometimes 29), strtotime(‘+1 month’) will return 3rd Mar.

The solution is adding “first day of” before the “+1 month”.

$date = strtotime('first day of +1 month');

 

Example:

// INCORRECT
$date = new DateTime('2012-01-31');
$date->modify('+1 month');
echo $date->format('F'); // return March

// CORRECT
$date = new DateTime('2012-01-31');
$date->modify('first day of +1 month');
echo $date->format('F'); // return February

 

Done =)

Reference: PHP: strtotime – Manual

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.