tags:

views:

40

answers:

4

I need to create next and previous link urls

here's a sample

<a href="/calendar/2009/10/">previous</a>
<? echo $_GET['month'].', '.$_GET['year']; // shows 11, 2009
<a href="/calendar/2009/12/">next</a>

where the 2nd segment is the year and the first segment is the month

I've got the month and the year in the GET array, but any ideas how best to do this?

I was thinking prevmonth = month-1, but then if the previous month was a new year, that would get all messed up.

A: 

Fairly easy to catch that sort of logic...? Just inc/dec the year if your month goes out of bounds...

#sanity check inputs
$month=min(max(intval($_GET['month']), 1),12);
$year=intval($_GET['year']);

$prev=array($month-1, $year);
if ($prev[0]==0)
{
    $prev[0]=12;
    $prev[1]--;
}
$next=array($month+1, $year);
if ($next[0]==13)
{
    $next[0]=1;
    $next[1]++;
}
Paul Dixon
A: 

I think the easiest way would just be to check for the "previous month < 1" condition and decrement the year. There might be a more clever way to do this, but this is easy enough to understand:

$prevyear = intval($_GET['year']);
$prevmonth = intval($_GET['month']) - 1;

// Check for year rollover.
if ( $prevmonth < 1 ) {
   $prevmonth = 12;
   $prevyear = $prevyear - 1;
}
Eric Petroelje
+2  A: 

You can use mktime with out-of-range values to do things like this. See the example #2 on the manual page.

e.g. echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997)); will give 1998-01-01.

notJim
Very slick this worked for me $prev_month = date("Y/n", mktime(0, 0, 0, $month - 1, 1, $year)); $next_month = date("Y/n", mktime(0, 0, 0, $month + 1, 1, $year));
mjr
+1  A: 

strtotime() makes it pretty easy.

$year = 2009;
$month = 5;

$nextMonth = strtotime('+1 Month', strtotime($year.'-'.$month.'-01'));

echo date('Y/m', $nextMonth);
timdev