我在想是否有任何容易和短缺方法來計算C++中兩個日期之間經過多少年的時間與提升?日期之間的區別(僅限於年)
例如(YYYY-MM-DD):
2005-01-01至2006-01-01 1年
2005-01-02至2006-01-01是0年
我可以很容易計算出,如果我認爲有沒有閏年通過使用這樣的代碼:
boost::gregorian::date d1(2005, 1, 1);
boost::gregorian::date d2(2006, 1, 1);
boost::gregorian::date_duration d3 = d1 - d2;
std::cout << abs(d3.days())/365;
但這樣的代碼2000年1月2日和2001-01-01之間的差值爲1年,當它應該是0,因爲2000年是閏年,我想考慮閏年。
//編輯
我想有一年爲一個整數。我建立了一個這樣的代碼(也就是現在我覺得工作),但還是如果有人有大約升壓比我更好的瞭解,我會爲一些優雅的解決方案感激:
boost::gregorian::date d1(2005, 4, 1);
boost::gregorian::date d2(2007, 3, 1);
int _yearsCount = abs(d1.year() - d2.year());
// I want to have d1 date earlier than d2
if(d2 < d1) {
boost::gregorian::date temp(d1);
d1 = boost::gregorian::date(d2);
d2 = temp;
}
// I assume now the d1 and d2 has the same year
// (the later one), 2007-04-01 and 2007-03-1
boost::gregorian::date d1_temp(d2.year(), d1.month(), d1.day());
if(d2 < d1_temp)
--_yearsCount;
你需要2.75461年嗎?或者你需要「約3年」?第一個問題是,除非你知道原始範圍,否則你無法取回確切的天數,所以它是沒用的。不妨將它除以365.25並完成它。 – Eugene 2013-03-19 19:34:02
我認爲需要* full *年的數量 - 即整數。 @tobi,請澄清! – Reunanen 2013-03-19 19:35:05
嘿,我編輯了這篇文章,感謝有趣的。 – tobi 2013-03-19 19:40:25