Page 1 of 1

Display Previus month

Posted: Sat Jan 18, 2003 9:23 am
by r4g3
Hi all,
I am currently trying to display on a page the previous month. I am getting the current month using getdate. Code is as follows:

$today=getdate();
$month = $today['month'];
$year = $today['year'];
$date = array_merge ("$month", "$year");
this works like a champ. However how could i go about displaying the previous month and year if applicable.
EX: date is January 2003. i want it to display December 2002. And when it is Feb i want to display Jan. I believe the mktime can do it I am just not understanding how. Any help will be greatly appreciated. Sorry if my code is malformed or erroneous. I am newbie to PHP. :]

use mon instead of month

Posted: Sat Jan 18, 2003 12:54 pm
by uberpolak
Change to this:

Code: Select all

<?php
$today=getdate(); 
$month = $today['mon'] - 1;
$year = $today['year']; 

switch ($month)
{
 case 0:
 $month = "December";
 $year -= 1;
 break;
 case 1:
 $month = "January";
 break;
 case 2:
 $month = "February";
 break;
 case 3:
 $month = "March";
 break;
 case 4:
 $month = "April";
 break;
 case 5:
 $month = "May";
 break;
 case 6:
 $month = "June";
 break;
 case 7:
 $month = "July";
 break;
 case 8:
 $month = "August";
 break;
 case 9:
 $month = "September";
 break;
 case 10:
 $month = "October";
 break;
 case 11:
 $month = "November";
 break;
}

$date = array_merge ("$month", "$year");
?>
When you use "mon" instead of "month" it gets a numerical value for the month, the "-1" would therefore decrement it one, the switch I added will convert $month to text before you set $date. I also set it to subtract one from the year if it finds that the previous month was December.

Posted: Sat Jan 18, 2003 12:56 pm
by hob_goblin

Code: Select all

$one = time() - 34214400;
echo date("F Y", $one);
should work.

Posted: Sun Jan 19, 2003 8:12 pm
by r4g3
uberpolak : Thanks for the help. However after playing with your code i found that i can change "mon" to "month" and do a "-1" on that without using the switch or case statements. Again, thanx for the help. Without your suggestion i never would have figured it out.

Posted: Mon Jan 20, 2003 1:29 pm
by puckeye
I have a nice code to do exactly what you want.

Code: Select all

$today=getdate(); 
$month = $today&#1111;'month']; 
$year = $today&#1111;'year']; 
$day = $today&#1111;'mday']; 
$date = array_merge ("$month", "$year"); 

$PreviousMonth = date("m Y", mktime("0, 0, 0, $month - 1, $day, $year));
As seen in MKTIME(); http://www.php.net/manual/en/function.mktime.php if you end up with a value of 0 for Month you'll end up with December of the previous year... Same thing with 0 for the Day ends up on the last day of the previous month...