Welcome to WebmasterWorld Guest from 54.196.238.210

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Help with Date Calculations in PHP

Dare I suggest this is a bug!

     

neiljones

10:06 pm on Mar 1, 2004 (gmt 0)

10+ Year Member



Can anyone suggest a reliable way of adding months on to dates in PHP?
That is my question really but look at what I have written below.

Ideally I want to add 3 months onto a given date but checking things out with 1 month gives me this headache.
Try this piece of code and you may see what I mean.
Where on earth did April go to!?
<?
$initialdate = mktime(0,0,0,03,31,2004);
print date("d-M-Y",$initialdate)."<br>";
for ($n=1;$n<=5;$n++)
{
$datemonths =date("m",$initialdate);
$datedays =date("d",$initialdate);
$dateyears =date("Y",$initialdate);
$datemonths =date("m",$initialdate);
print "DATEMONTHS ".$datemonths."<BR>";
print "DATEMONTHS PLUS ONE ".($datemonths+1)."<BR>";
$initialdate = mktime (0,0,0,($datemonths+1),$datedays,$dateyears);

print date("d-M-Y",$initialdate)."<BR>";
}
?>

31-Mar-2004
DATEMONTHS 03
DATEMONTHS PLUS ONE 4
01-May-2004
DATEMONTHS 05
DATEMONTHS PLUS ONE 6
01-Jun-2004
DATEMONTHS 06
DATEMONTHS PLUS ONE 7
01-Jul-2004
DATEMONTHS 07
DATEMONTHS PLUS ONE 8
01-Aug-2004
DATEMONTHS 08
DATEMONTHS PLUS ONE 9
01-Sep-2004

coopster

10:25 pm on Mar 1, 2004 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Dare not! :)

There are only 30 days in April. You have to take your day of the month into account during your loop here. See what April 31, 2004 gets you?

$initialdate = mktime (0,0,0,4,31,2004); 
print date("d-M-Y",$initialdate)."<BR>";
// prints:
// 01-May-2004

Have faith, the date function will give you what you want.

Oops, almost forgot! I often use the strtotime [php.net] function for date calculations:

$month = date("F"); 
$next = date("F", strtotime("+1 month"));
 

Featured Threads

Hot Threads This Week

Hot Threads This Month