PHP obtaining the next month, date-string parser

The correct way of obtaining next month correctly is by using “first day of next month” or using “last day of next month”.

$n = new DateTime( '2010-01-31' );
$n->modify( 'first day of next month'  );
echo $n>format( 'F' ), "\n";

In normal case, user next month in php to obtain next month value doesn’t work as expected, but it skips to month after next month, Example:

$n = new DateTime( '2010-01-31' );
$n->modify( 'next month' );
echo $n>format( 'F' ), "\n";

Output will be: March. Which suppose to be February.

March obviously doesn’t follow January as February is in between. However, the above behavior is correct. The following happens internally:
•next month increases the month number (originally 1) by one. This makes the date 2010-02-31.
•The second month (February) only has 28 days in 2010, so PHP auto-corrects this by just continuing to count days from February 1st. You then end up at March 3rd.
•The formatting strips off the year and day, resulting in the output March.
This can easily be seen when echoing the date with a full date format,

echo $d->format( 'F jS, Y' ), "\n";

which will output March 3rd, 2010.

Another post to obtain next month first day using mktime here.

By Keenlio, March 26, 2014

What do you think?

Leave a Reply

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


8 + one =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>