旧问题的新答案:
使用这个C++11/C++14 header-only date library,你现在可以写:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
auto x = 2012_y/1/24;
auto y = 2013_y/1/8;
cout << x << '\n';
cout << y << '\n';
cout << "difference = " << (sys_days{y} - sys_days{x}).count() << " days\n";
}
哪些输出:
2012-01-24
2013-01-08
difference = 350 days
如果您不想依赖此库,您可以编写自己的库,使用与上述日期库相同的日期算法。它们在本文中找到:chrono-Compatible Low-Level Date Algorithms。本例中使用的本文算法是这样的:
// Returns number of days since civil 1970-01-01. Negative values indicate
// days prior to 1970-01-01.
// Preconditions: y-m-d represents a date in the civil (Gregorian) calendar
// m is in [1, 12]
// d is in [1, last_day_of_month(y, m)]
// y is "approximately" in
// [numeric_limits<Int>::min()/366, numeric_limits<Int>::max()/366]
// Exact range of validity is:
// [civil_from_days(numeric_limits<Int>::min()),
// civil_from_days(numeric_limits<Int>::max()-719468)]
template <class Int>
constexpr
Int
days_from_civil(Int y, unsigned m, unsigned d) noexcept
{
static_assert(std::numeric_limits<unsigned>::digits >= 18,
"This algorithm has not been ported to a 16 bit unsigned integer");
static_assert(std::numeric_limits<Int>::digits >= 20,
"This algorithm has not been ported to a 16 bit signed integer");
y -= m <= 2;
const Int era = (y >= 0 ? y : y-399) / 400;
const unsigned yoe = static_cast<unsigned>(y - era * 400); // [0, 399]
const unsigned doy = (153*(m + (m > 2 ? -3 : 9)) + 2)/5 + d-1; // [0, 365]
const unsigned doe = yoe * 365 + yoe/4 - yoe/100 + doy; // [0, 146096]
return era * 146097 + static_cast<Int>(doe) - 719468;
}
请参阅chrono-Compatible Low-Level Date Algorithms,了解有关此算法如何工作、对其进行单元测试及其有效性范围的详细信息。
此算法模拟proleptic Gregorian calendar,它无限期地扩展公历,向前和向后。要建模其他日历(例如儒略历),您将需要其他算法,such as the ones shown here。一旦你设置了其他日历,并同步到同一个系列纪元(这些算法使用 1970-01-01 Gregorian,这也是 Unix time 纪元),你就可以轻松地计算出任何两个日期之间的天数,但也可以在您建模的任意两个日历之间。
这使您不必在从儒略到公历转换的日期中硬编码。您只需要知道您的输入数据是针对哪个日历引用的。
有时历史文档中可能不明确的日期会用Old Style / New Style 进行注释,以分别表示儒略历或公历。
如果您还关心日期的时间,这个same date library 与<chrono> 库无缝集成以使用hours、minutes、seconds、milliseconds、@987654342 @ 和nanoseconds,并用system_clock::now() 获取当前日期和时间。
如果您关心时区,则在date library 之上写一个额外的(单独的)timezone library 以使用IANA timezone database 处理时区。如果需要,timezone library 还具有计算功能,包括 leap seconds。