2013-03-19 32 views
0

我在想是否有任何容易和短缺方法來計算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; 
+0

你需要2.75461年嗎?或者你需要「約3年」?第一個問題是,除非你知道原始範圍,否則你無法取回確切的天數,所以它是沒用的。不妨將它除以365.25並完成它。 – Eugene 2013-03-19 19:34:02

+0

我認爲需要* full *年的數量 - 即整數。 @tobi,請澄清! – Reunanen 2013-03-19 19:35:05

+0

嘿,我編輯了這篇文章,感謝有趣的。 – tobi 2013-03-19 19:40:25

回答

3

假設你想要的整年數(0,1,或更多),怎麼樣:

if (d1 > d2) 
    std::swap(d1, d2); // guarantee that d2 >= d1 

boost::date_time::partial_date pd1(d1.day(), d1.month()); 
boost::date_time::partial_date pd2(d2.day(), d2.month()); 

int fullYearsInBetween = d2.year() - d1.year(); 
if (pd1 > pd2) 
    fullYearsInBetween -= 1; 

雖然這基本上等於你的算法(你編輯的職位,我在寫這一段時間)。

+0

是的,這個想法是一樣的,儘管你的代碼更乾淨。 – tobi 2013-03-19 19:52:01

+0

是的,std :: swap值得借鑑。 – Reunanen 2013-03-19 19:53:56