homepage Welcome to WebmasterWorld Guest from 54.204.90.135
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Help with Date Calculations in PHP
Dare I suggest this is a bug!
neiljones




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

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




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

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"));

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved