tags:

views:

182

answers:

1

I've used boost::gregorian::date a bit now.

I can see that there are the related months & years & weeks duration types. I can see how to use known durations to advance a given date.

Qu: But how can I get the difference between two dates in months (or years or weeks) ?

I was hoping to find a function like:

template<typename DURATION>
  DURATION date_diff<DURATION>(const date& d1,const date& d2);

There would need to be some handling of rounding too.

This function would return the number of (say) whole months between d1 and d2.

+5  A: 

Do you mean difference between dates (09/12 - 08/05 = 01/07 = 19months) or difference in time ((date2_seconds - date1_seconds) / seconds_per_month)?

For the first case it's possible to use accessors

greg_year date::year() const;
greg_month date::month() const;

Then difference between dates in months:

int months = (data2.year() - date1.year())*12 + date2.month() - date1.month()

For the second case you there is operator

date_duration date::operator-(date) const;

And date_duration has following useful member:

long date_duration::days() const;

So you can do like this:

//date date1, date2
int months = (date2-date1).days()/30;
buratinas
Yes, sorry if that wasn't clear. I mean the number of months between two dates. (Either rounded up or down, in some way.)I'll clarify the question.BTW, the last line of code gives number of days, not months, right? Is it more clearly written as num_days rather than months? E.g. : int num_days = (date2-date1).days();
MartinP
yes, that was my mistake :) now it's corrected a bit.Actually if you want correct number of months for long periods it's better to use 365.25/12 instead of 30.
buratinas
Thanks for the tought, but sorry, I'm not convinced by that approach.Any treatment based on all months are aprox the same length will get it wrong in a few special cases. Like the pathological case of February in a leap year.If I took d1 to be 30-Jan and d2 to be 1-Mar, then the separation in days would be 28 (on a leap year). Looking only at that figure of 28 days, we can not know if the two dates are in the same month or possibly separated by all of Febuary.That's why I think we'd need a Gregorian calendar to work out how many whole calendar months are between two dates.
MartinP
Finally I fully understood your question. Then it's possible to use date::year() and date::month() accessors and difference between dates in months is int months = (data2.year() - date1.year())*12 + date2.month() - date1.month()
buratinas
the months formula above is also how excel calculates this value
Steve
Ah yes! Now I see it. (I think I should have figured that out.) :-| Thanks
MartinP