tags:

views:

111

answers:

3

I have a date such as 2009-06-30 (30th june, 2009). I want to calculate a date which appears 2 months, and 3 days before or after the first date. Or, 3 months, 6 days, before or after, etc. How can I do this? Is there an easy way using DATE_SUB() or DATE_ADD()

+2  A: 

DATE_ADD(whatever, INTERVAL 2 MONTH) + INTERVAL 3 DAY for example (just to show both of the syntax variants you can use in MySQL for this task) will give a date that's 2 months and 3 days after whatever.

Alex Martelli
Awesome. Do I need to be particular about whether I add/subtract the days before the months or not, etc? Or will it calculate the same date in the end?
Click Upvote
No guarantees: `select '2009-01-30' - interval 1 day + interval 1 month` says 2009-02-28, but `select '2009-01-30' + interval 1 month - interval 1 day;` says 2009-02-27. "Adding N months" is not a clearly defined mathematical operation, since months are of different lengths, so there's some "fuzzy maths" there;-).
Alex Martelli
A: 

Zend_Date is great for this kind of thing. Zend_Date is part of the Zend_Framework, and you can just use the Zend_Date part, you don't have to use the whole part of the framework.

You can add days or months to a date and it will handle all the complexities for you. It's much easier than any other method I've found in PHP.

Kekoa
A: 

You should be able to use DateTime:sub. To get the date 3 months and six days you should be able to use:

date_sub($myDate,"P3M6D");
Kibbee