Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding Dates

Status
Not open for further replies.

jsnull

IS-IT--Management
Feb 19, 2002
99
0
0
US
Any advice on easy way to do date addition in PHP, such as:

$newday = $todayis + 10days

And, how about the reverse:

$oladday = $todayis - 10days

Can't seem to find anything anywhere that is simple. Suggestions most appreciated.



Jim Null
[afro]
 
Check out the date() function. Specifically example 437.


-- -- -- -- -- -- -- --

If you give someone a program, you will frustrate them for a day
but if you teach them how to program, you will frustrate them for a lifetime.
 
actually, not sure that date will help on its own

try this instead

Code:
$newdate = date ("`Y-m-d", strtotime("+10 days"));

this assumes the calculation is done from today.

check out strtotime().
 
I should have explained it a little better...

Example 437 shows how the functions date() and mktime() can be used together to add and subtract time.

Code:
//ten days ahead
$lastmonth = mktime(0, 0, 0, date("m"), date("d")+10,   date("Y"));

//ten days back
$lastmonth = mktime(0, 0, 0, date("m"), date("d")-10,   date("Y"));

This can probably be optimized to run faster but it should get the job done.


-- -- -- -- -- -- -- --

If you give someone a program, you will frustrate them for a day
but if you teach them how to program, you will frustrate them for a lifetime.
 
Thank you both ... I very much appreciate your help. Both of your replies got me on the right track. Here is what I finally settled on using:

Code:
<?php
// ten days from today

$todayis = date('Y-m-d');
$newdateis = $todayis + strtotime("+10 days");
$newdateis = date('Y-m-d', $newdateis);

print "<strong>10 Days From Today</strong><br>";
print "Today: $todayis<br>";
print "New Date: $newdateis<br><br>";

// ten days before a date

$todayis = date('Y-m-d');
$newdateis = $todayis + strtotime("-10 days");
$newdateis = date('Y-m-d', $newdateis);

print "<strong>10 Days Before Today</strong><br>";
print "Today: $todayis<br>";
print "New Date: $newdateis<br><br>";

?>

Jim Null
[afro]
 
these lines
Code:
$todayis = date('Y-m-d');
$newdateis = $todayis + strtotime("-10 days");
can be simplified
Code:
$todayis = date("Y-m-d");
$newdateis = strtotime("-10 days");

to subtract ten days from another date use this structure
Code:
$date = "2007-01-01";
$fewdaysbefore = date("Y-m-d", strtotime("-10 days", strtotime($date)));
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top