Page 1 of 1

[solved] Previous/Next month driving me round the bend

Posted: Tue Feb 27, 2007 3:56 pm
by andym01480
I have been fiddling with date and time functions ready to have a go at a calendar.

I can't seem to get the previous/next links below to role round the years at Jan and Dec.
In other words...The months roll forwards and backwards, but not the year!

What am I doing wrong please?

Code: Select all

<?php
// Today's month
$m=date("m");
//if previous or next press then used that value for the "current" month
if (isset($_REQUEST['m'])){
$m=date("m",intval($_REQUEST['m']));
}

// timestamps 
$current = mktime(0, 0, 0, $m);
$next = mktime(0, 0, 0, $m+1);
$previous = mktime(0, 0, 0, $m-1);

// so I can read it!
$now=date("d M Y",$current);

//The links 
echo "<a href=\"test.php?m=$previous\">Previous</a>Current month selected $now <a href=\"test.php?m=$next\">Next</a>";
?>

Posted: Tue Feb 27, 2007 3:59 pm
by pickle
strtotime() is a godsend.

Posted: Tue Feb 27, 2007 4:27 pm
by andym01480
Yes it is and my logic was skewed too!

Code: Select all

<?php
$current=mktime();
if (isset($_REQUEST['m'])){
$current=intval($_REQUEST['m']);
}

$next = strtotime("+1 month",$current);
$previous = strtotime("-1 month",$current);

$now=date("d M Y",$current);
echo "<a href=\"test.php?m=$previous\">Previous</a>Current month selected $now <a href=\"test.php?m=$next\">Next</a>";
?>

Posted: Tue Feb 27, 2007 4:53 pm
by pickle
Heh, I just spent 10 minutes on a reply that basically boiled down to telling you your logic was skewed - ha!

I can see you've fixed it now. One optimization you can do though is with regards to setting $current:

Code: Select all

$current=(isset($_GET['m'])) ? intval($_GET['m']) : time();
I'm not sure which one is faster, time() or mktime(), but I'd recommend using time() instead when you want a timestamp for 'now'.

Posted: Tue Feb 27, 2007 4:57 pm
by andym01480
Thank you so much.