views:

49

answers:

2

I have a boost::posix_time::ptime that points to March 31st 2010 like this:

ptime p(date(2010, Mar, 31));

I would like to subtract a month (and possibly years) from this date. From the docs I see these two operators: ptime operator-(time_duration) and ptime operator-(days) but none of them can work with months/years. If I try and do:

time_duration duration = hours(24 * 30);
ptime pp = p - duration;

I'm getting March 1st and if I'm trying:

ptime pp = p - days(30);

I'm still getting March 1st, while I'd like to get February 28th.
How can I achieve my desired result? (I would like to get the desired result also when subtracting a month from March 28, 29, 30)

+3  A: 

boost::posix_time::ptime::date() operator returns date object. You can call greg_year, greg_month etc. for this object.

Alex Farber
Thanks, your suggestion led me to the solution. Using the `boost::gregorian::date` class I was able to find "date durations", that have weeks/months/years.
Zack
A: 

Well, I guess you already know that not all months have 30 days so you can't subtract with 30 days in general.

You should ask yourself what you mean by "subtract a month".

Peter Jansson
I already said in my question my interpretation of "subtract a month", which to my knowledge is the standard one.
Zack
So by subtracting one month from February 5, you mean January 5?And by subtracting one month from March 30, you mean February 30, or...? I am sorry, I was not aware there was a standard interpretation of subtracting a month. What is that standard interpretation anyway?
Peter Jansson
Subtracting one month from March 30 would give you February 28 or February 29, depending on the year.I can refer you to http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/gregorian.html#snap_to_details where they explain this behavior, which may seem somewhat "awkward" at first, but is what you would expect
Zack