Jump to content

Months not calculating correctly.


bsamson

Recommended Posts

I have the following script:

 

<?php
  // Get last 3 months for search criteria
  $longMonth1 = date("M Y");
  $longMonth2 = date("M Y",strtotime("-1 month"));

  echo $longMonth1."<br>".$longMonth2;
?>

 

  This was working fine the other day, however today (03/31/2008) it is displaying:

  Mar 2008

  Mar 2008

 

  It should display:

  Mar 2008

  Feb 2008

 

  Any suggestions will be greatly appreciated!

Link to comment
https://forums.phpfreaks.com/topic/98824-months-not-calculating-correctly/
Share on other sites

Because 02/31/2008 does not exist (today - 1 month) you get the next valid date (the start of this month.)

 

The php manual recommends forming a date in the current month that would always exist (they used the  15th, but anything from the 1st to the 28th would work) and then subtract one month.

 

You might also want to consider using the mktime() function -

 

echo date("M Y",mktime(0, 0, 0, date("m"), 1, date("Y")));
echo date("M Y",mktime(0, 0, 0, date("m")-1, 1, date("Y")));

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.