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
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")));

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.