日期(仅限年份)之间的差异
Difference between dates (years only) in boost
我想知道是否有任何简单而简短的方法来计算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;
假设您想要完整年数(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;
虽然这基本上等于你的算法(当我写这篇文章的时候你在编辑文章)
相关文章:
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- 日期和当前日期之间的差异
- CPP 程序二查找两个给定日期之间的天数,conol CMD
- Qml - c++ 类和 QmlRegisterType 创建的类之间的交换日期
- 十进制格式的日期之间的差异
- 解决方案在两个日期之间的天数内不起作用
- 使用 c++ 获取两个日期与时间字符串之间的差异(以秒为单位)
- 计算当前日期和用户输入日期问题之间的天数
- C 的两个日期之间的差异
- 如何使用C Win32 API计算两个日期之间的天数
- C++计算日期之间的差异
- 两个日期之间的 C++ 日期差异
- v8::值到日期之间的转换
- 两个对象之间的日期比较
- 确定日期之间的差异
- C++ 给定日期和今天日期之间的天数
- 找出日期之间的差异,并将其归类
- c++获取用户选择的日期与实际日期之间的年份(计算日、月、年)
- 两个日期之间的总天数
- 设计一个结构来存储时间和日期.写一个函数来计算两个时间之间的差(以分钟为单位)