日历库C ++

时间:2016-09-24 10:33:39

标签: c++ date calendar

我最近使用QUANTLIB C ++中的Calendar函数来执行以下操作。

不幸的是,任何使用QUANTLIB的项目都需要很长时间才能编译。我有兴趣以多种不同的格式解释日期字符串(quantlib使我能够这样做),如下所示。我也希望找到不同格式的各种日期之间的区别等。

我的问题是,是否有另一个C ++库可以让我做所有这些事情(希望能更快地在我的项目中编译)?

以下简单项目似乎需要永远编译。

我唯一的先决条件是静态编译。

#include <iostream>
#include <ql/quantlib.hpp>
#include <ql/utilities/dataparsers.hpp>


using namespace std;
using namespace QuantLib;

int main()
{

    Calendar cal = Australia();
    const Date dt(21, Aug, 1971);

    bool itis = false;

    itis = cal.isBusinessDay(dt);
    cout << "business day yes? " << itis << endl;
    cout << "The calendar country is: " << cal.name() << endl;


    // now convert a string to a date.
    string mydate = "05/08/2016";
    const Date d = DateParser::parseFormatted(mydate,"%d/%m/%Y");


    cout << "The year of this date is: " <<  d.year() << endl;
    cout << "The month of this date is: " <<  d.month() << endl;
    cout << "The day of this date is: " <<  d.dayOfMonth() << endl;
    cout << "The date " << mydate << " is a business day yes? " << cal.isBusinessDay(d) << endl;


}

1 个答案:

答案 0 :(得分:3)

这个date library是完全记录的,开源的,你需要的部分只是标题,编译速度非常快。它需要C ++ 11或更高版本,因为它构建于<chrono>

您的示例如下所示:

#include "date/date.h"
#include <iostream>
#include <sstream>

using namespace std;
using namespace date;

int main()
{
    const auto dt = 21_d/aug/1971;
    auto wd = weekday{dt};

    auto itis = wd != sun && wd != sat;
    cout << "business day yes? " << itis << endl;

    // now convert a string to a date.
    istringstream mydate{"05/08/2016"};
    local_days ld;
    mydate >> parse("%d/%m/%Y", ld);
    auto d = year_month_day{ld};
    wd = weekday{ld};

    cout << "The year of this date is: " <<  d.year() << '\n';
    cout << "The month of this date is: " <<  d.month() << '\n';
    cout << "The day of this date is: " <<  d.day() << '\n';
    cout << "The date " << d << " is a business day yes? " << (wd != sun && wd != sat) << '\n';
}

上述程序输出:

business day yes? 0
The year of this date is: 2016
The month of this date is: Aug
The day of this date is: 05
The date 2016-08-05 is a business day yes? 1

唯一粗略的部分是缺少isBusinessDay。但是在这个库中很容易找到星期几(如上所示)。如果您有澳大利亚的假期列表,您可以轻松使用此库来构建更完整的isBusinessDay。例如:

bool
isBusinessDay(year_month_day ymd)
{
    sys_days sd = ymd;
    weekday wd = sd;
    if (wd == sat || wd == sun)  // weekend
        return false;
    if (sd == mon[2]/jun/ymd.year())  // Queen's Birthday
        return false;
    // ...
    return true;
}