日期(仅限年份)之间的差异

Difference between dates (years only) in boost

本文关键字:之间 日期      更新时间:2023-10-16

我想知道是否有任何简单而简短的方法来计算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;

虽然这基本上等于你的算法(当我写这篇文章的时候你在编辑文章)