【问题标题】:weekdays' duration using boost date使用提升日期的工作日持续时间
【发布时间】:2011-09-07 21:55:33
【问题描述】:

有没有办法只得到否。 2 个提升日期之间的工作日数。

在下面,我只得到日历日。

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;

【问题讨论】:

    标签: c++ boost boost-date-time


    【解决方案1】:

    也许最简单的方法是从头到尾运行一个 day_iterator:

    #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";
    }
    

    【讨论】:

    • 创建一个is_weekday 函数,这变成了如何使用count_if 的一个很好的例子。
    • int result = std::count_if(begin_dt, end_dt, [](date&amp; d) { d.day_of_week != boost::date_time::Saturday &amp;&amp; d.day_of_week != boost::date_time::Sunday; });.
    • @Dennis Zickefoose 没那么简单,boost::gregorian::day_iterator 与普通迭代器不兼容。
    【解决方案2】:

    您可以开始减去下周开始的天数,然后删除 1 或 2,具体取决于您是在星期六还是之前,还是星期天。然后,您可以将剩余的天数除以 7,将该数字乘以 2,然后减去天数。您还必须为其余部分提出理由。如果是 6(星期六),您必须再删除一个。不容易,但你明白了。

    【讨论】:

    • 确实如此,虽然我希望有一种更直接的方法;-)
    猜你喜欢
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2014-02-18
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多