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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

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

Post 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>";
?>
Last edited by andym01480 on Tue Feb 27, 2007 4:44 pm, edited 1 time in total.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

strtotime() is a godsend.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Post 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>";
?>
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post 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'.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Post by andym01480 »

Thank you so much.
Post Reply