【发布时间】:2013-03-19 19:00:08
【问题描述】:
我想知道是否有任何简单而简短的方法来计算 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-01-02 和 2001-01-01 之间的差异是 1 年,而它应该是 0,因为 2000 年是闰年,我想考虑闰年。
// 编辑
我想将年份设为整数。我已经创建了这样的代码(我认为现在可以使用),但是如果有人比我对 boost 有更好的了解,我会很感激一些优雅的解决方案:
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 并完成它。
-
我认为需要 full 年 - 即整数。 @tobi,请澄清!
-
嘿,我已经编辑了帖子,感谢您的关注。
-
那么,这是否意味着 (2000-02-28) - (2001-02-27) 是 1 年,但 (2000-03-28) - (2001-03-27) 是 0年?
-
@Eugene 都是 0 年。