PHP get last month in March bug

This post is not laravel related, but is a big bug in PHP regarding how it handles months, especially February.

If you need  the last month, today(March 29), with one of the following ways



 date('Y-m-d', strtotime('-1 Month'));

 date('Y-m-d', mktime(0,0,0,date("m")-1,date("d"),date("Y")) );

 $date = new DateTime();
 $date->modify("-1 Month");
 $date->format("Y-m-d");


They all return “2013-03-01”, which can screw up your applications big time.

The solution is:


 date('Y-m-d', strtotime('first day of last month'));

Which returns “2013-02-01”;

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s