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 sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding months to a date

Status
Not open for further replies.

jsteiner87

Programmer
Oct 9, 2003
76
US
I have a date being stored in a MYSQL database. I want to take that day and add months to it. How do you go about doing this? It is stored as a Date (MM-DD-YYYY) in the database.
 
Sorry about that, it is stored as YYYY-MM-DD. I have no idea what I was thinking.
 
I don't guess the version matters.

Given a table foo which contains:

[tt]+----+---------------------+
| Id | the_stamp |
+----+---------------------+
| 1 | 2006-01-30 10:15:00 |
| 2 | 2006-02-28 10:30:00 |
| 3 | 2006-03-15 10:45:00 |
+----+---------------------+
[/tt]

The query:

select date_add(the_stamp, interval 1 MONTH) as new_date from foo;

will return:

[tt]+---------------------+
| new_date |
+---------------------+
| 2006-02-28 10:15:00 |
| 2006-03-28 10:30:00 |
| 2006-04-15 10:45:00 |
+---------------------+
[/tt]


Want the best answers? Ask the best questions! TANSTAAFL!
 
Is there a way to do it with PHP. I have a variable that contains the amount of months that I would like to add to the date. The amount of month can change.
 
Trust me, you want to do this on the MySQL side. It handles data-math more easily than PHP.

Programmatically generate the query from PHP:

If $number_of_months contains the number of months to add, then:

$query = "select date_add(the_stamp, interval " . $number_of_months . " MONTH) as new_date from foo";

Will produce whatever query you need. You script can pass this query to MySQL and fetch the return.




Want the best answers? Ask the best questions! TANSTAAFL!
 
I agree with sleipnir214 on using mysql for d/t manipulations.

if you must do it in php then you could try this (i have not tested this in <PHP5):

Code:
<?
$olddate = "2006-06-01";
$newdate = date("Y-m-d", strtotime("+1 month", strtotime($olddate)));
echo $newdate;
?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top