开发者

number of months between two dates - using boost's date

开发者 https://www.devze.com 2022-12-28 00:24 出处:网络
I\'ve used boost::gregorian::date a bit now. I can see that there are the related months & years & weeks duration types.

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 开发者_如何学Cand d2.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消