Jump to content

Help with getting prior month...


savagenoob

Recommended Posts

OK, since today is the 31st, I guess I figured out that strtotime("-1 Month') really only goes back 30 days, so where I think it should be September, its registering October 1st. Is there a fix for this?

$month = date('F Y', strtotime("-1 month"));
$month1 = date('F Y', strtotime("-2 month"));
$month2 = date('F Y', strtotime("-3 month"));
$month3 = date('F Y', strtotime("-4 month"));
$month4 = date('F Y', strtotime("-5 month"));
$month5 = date('F Y', strtotime("-6 month"));

Link to comment
Share on other sites

You need to start with a day in the month that always exists, than apply -1 month, -2 month, ...  mktime is actually easier to use. You can list the first day of the current month, then subtract 1, 2, 3,... from the month parameter.

 

Edit: like so -

<?php

for($x = 1;$x <=6;$x++){
echo date('F Y', mktime(0,0,0,date("n")-$x,1,date("Y")));
echo "<br />";
}

Link to comment
Share on other sites

Yeah, use mktime() - much faster than strtotime(). I would suggest a loop and storing the results in an array, but with what you had above this would work

 

$monthInt = intval(date('n'));
$yearInt = intval(date('Y'));

$month =  date('F d Y H:i:s', mktime(12, 0, 0, $monthInt-1, 1, $yearInt))."<br>\n";
$month1 =  date('F d Y H:i:s', mktime(12, 0, 0, $monthInt-2, 1, $yearInt))."<br>\n";
$month2 =  date('F d Y H:i:s', mktime(12, 0, 0, $monthInt-3, 1, $yearInt))."<br>\n";
$month3 =  date('F d Y H:i:s', mktime(12, 0, 0, $monthInt-4, 1, $yearInt))."<br>\n";
$month4 =  date('F d Y H:i:s', mktime(12, 0, 0, $monthInt-5, 1, $yearInt))."<br>\n";
$month5 =  date('F d Y H:i:s', mktime(12, 0, 0, $monthInt-6, 1, $yearInt))."<br>\n";

 

Note, that if the result of $month-x is a negative value it will calculate correctly. So, January (1) with a -2 will result in November.

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.