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()
views:
111answers:
3
+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
2009-05-31 01:56:25
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
2009-05-31 02:01:39
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
2009-05-31 02:08:26
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
2009-05-31 01:57:09
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
2009-05-31 02:01:54