c++ - 获取两天之间的交易日数

标签 c++ boost c++11

我正在尝试获取两个日期之间的交易日期数量,这将只排除周末并且不会考虑任何假期。我正在使用 Boost 和 c++11 标准。

using namespace boost::gregorian;
long dateDifference( string start_date, string end_date ) {

            date _start_date(from_simple_string(start_date));
            date _end_date(from_simple_string(end_date));


            long difference = ( _start_date - _end_date ).days();

            return difference;

        }

这只返回两个日期之间的天数,不考虑周末。有人能指出我正确的方向吗?我似乎无法找出解决方案。

谢谢, 最大

最佳答案

没有循环的 O(1) 解决方案:

#include <boost/date_time.hpp>
using namespace std;
using namespace boost::gregorian;

long countWeekDays( string d0str, string d1str ) {
    date d0(from_simple_string(d0str));
    date d1(from_simple_string(d1str));
    long ndays = (d1-d0).days() + 1; // +1 for inclusive
    long nwkends = 2*( (ndays+d0.day_of_week())/7 ); // 2*Saturdays
    if( d0.day_of_week() == boost::date_time::Sunday ) ++nwkends;
    if( d1.day_of_week() == boost::date_time::Saturday ) --nwkends;
    return ndays - nwkends;
}

基本思路是先统计所有星期六,公式(ndays+d0.day_of_week())/7可以方便地给出。将此值加倍即可获得所有星期六和星期日,但开始和结束日期可能落在周末的情况除外,这会通过 2 个简单测试进行调整。

测试它:

#include <iostream>
#include <cassert>
#include <string>

//      January 2014    
//  Su Mo Tu We Th Fr Sa
//            1  2  3  4
//   5  6  7  8  9 10 11
//  12 13 14 15 16 17 18
//  19 20 21 22 23 24 25
//  26 27 28 29 30 31
int main()
{
  assert(countWeekDays("2014-01-01","2014-01-01") == 1);
  assert(countWeekDays("2014-01-01","2014-01-02") == 2);
  assert(countWeekDays("2014-01-01","2014-01-03") == 3);
  assert(countWeekDays("2014-01-01","2014-01-04") == 3);
  assert(countWeekDays("2014-01-01","2014-01-05") == 3);
  assert(countWeekDays("2014-01-01","2014-01-06") == 4);
  assert(countWeekDays("2014-01-01","2014-01-10") == 8);
  assert(countWeekDays("2014-01-01","2014-01-11") == 8);
  assert(countWeekDays("2014-01-01","2014-01-12") == 8);
  assert(countWeekDays("2014-01-01","2014-01-13") == 9);
  assert(countWeekDays("2014-01-02","2014-01-13") == 8);
  assert(countWeekDays("2014-01-03","2014-01-13") == 7);
  assert(countWeekDays("2014-01-04","2014-01-13") == 6);
  assert(countWeekDays("2014-01-05","2014-01-13") == 6);
  assert(countWeekDays("2014-01-06","2014-01-13") == 6);
  assert(countWeekDays("2014-01-07","2014-01-13") == 5);
  cout << "All tests pass." << endl;
  return 0;
}

这适用于 Gregorian calendar 中的任何日期范围,目前支持 1400-10000 年。请注意,不同的国家在不同的时间采用了公历。例如,英国人在 1752 年 9 月从儒略历改为公历,所以他们那个月的日历看起来像这样

   September 1752
Su Mo Tu We Th Fr Sa
       1  2 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

关于c++ - 获取两天之间的交易日数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22270691/

相关文章:

c++ - boost 异常的错误信息

c++ - 指向成员的指针,在类中

c++ - 使用 SFINAE 检测 constexpr

c++ - 侵入式数据结构中的成员钩子(Hook)与基本钩子(Hook)

c++ - std::unique_ptr 在虚拟析构函数上重置 SIGABRT

c++ - fatal error comp.h 未找到 Netbean 8.0

c++ - 澄清 `boost::bind`和 `this`的使用

c++ - 非急切克林星 boost 灵气

c++ - 这些位在内存中是如何解释的

c++ - 当对象绑定(bind)到成员函数时,为什么 std::function 会调用析构函数?