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
https://forums.phpfreaks.com/topic/250188-help-with-getting-prior-month/
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 />";
}

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.

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.