weekdays' duration using boost date

家住魔仙堡 提交于 2019-12-01 07:32:44

问题


Is there a way to get only the no. of weekdays between 2 boost dates.

In the following, I'm only getting calendar days.

date begin_dt(2011,Aug,3);
date end_dt(day_clock::local_day());
days duration=end_dt-begin_dt;

std::cout<<"calendar days between begin & end date are: "<<duration<<std::endl;

回答1:


Perhaps the simplest way is to run a day_iterator from start to finish:

#include <iostream>
#include <boost/date_time.hpp>
int main()
{
    using namespace boost::gregorian;

    date begin_dt(2011,Aug,3);
    date end_dt(day_clock::local_day());
    days duration=end_dt-begin_dt;

    std::cout<<"calendar days between begin & end date are:" << duration << '\n';

    int cnt=0;
    for(day_iterator iter = begin_dt; iter!=end_dt; ++iter)
    {
        if(    iter->day_of_week() !=  boost::date_time::Saturday
            && iter->day_of_week() !=  boost::date_time::Sunday)
            ++cnt;
    }
    std::cout << "of them " << cnt << " are weekdays\n";
}



回答2:


You could start substracting the number of days to the next week start, and deleting either 1 or two depending if you're on saturday or before, or sunday. Then, you can divide the rest of the days remaining by 7, multiply that number by 2, and substract to the days. You have to make a case for the remainder too. If it is 6 (saturday), you have to remove one more. Not easy, but you get the idea.



来源:https://stackoverflow.com/questions/7340986/weekdays-duration-using-boost-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!