BOOST 日期时间库 之 日期长度与日期区间 2/3

来源:互联网 发布:dnf额外暴击伤害算法 编辑:程序博客网 时间:2024/06/06 15:50
一、日期长度 boost::gregorian::date_duration
//--------------------------
1、摘要
日期长度是以天为单位的时长,是度量时间长度的一个标量,是一个天数的计量。它与日期不同,值可以是任意整数,
可正可负。


2、使用
为date_duration定义了一个常用的typedef:days,如下:
boost::gregorian::date_duration dd1(10);
boost::gregorian::days dd2(20);


3、扩展
提供了months、years、weeks等另外三个时长类,分别用来表示n个月、n个年、n个星期
months和years全面支持加减乘除运算,使用成员函数number_of_months()和number_of_years()
可获得表示的月数和年数。
boost::gregorian::weeks w(3); //3个星期
assert( w.days() == 21 );


boost::gregorian::months m(5); //5个月
boost::gregorian::years y(2); //2年


boost::gregorian::months m2 = y + m; //2年零5个月
assert( m2.number_of_months() == 29 );
assert( (y*2).number_of_years() == 4 );


4、日期运算
boost::gregorian::date d41(2000,1,1), d42(2008,8,8);
std::cout << d42 - d41 << std::endl; //3142天
assert( d41 + (d42-d41) == d42 );


d41 += boost::gregorian::days(10); //2000-1-11
assert( d41.day() == 11 );


d41 += boost::gregorian::months(2); //2000-3-11
assert( d41.month() == 3 && d41.day() == 11 );


d41 -= boost::gregorian::weeks(1); //2000-3-4
assert( d41.day() == 4 );


d42 -= boost::gregorian::years(7); //2001-8-8
assert( d42.year() == d41.year() + 1 );


【注意】
在于months、years这两个时长类进行计算时要注意:如果日期是月末的最后一天,
那么加减月或年会得到同样的月末时间,而不是简单的月份或者年份加1,这是合乎生活常识的。
但是,当天数是月末的28、29时,如果加减月份到2月份,那么随后的运算就总是月末的操作,
原来的天数信息就会丢失。如下:
boost::gregorian::date d44( 2010, 3, 30 );
d44 -= boost::gregorian::months(1); //2010-2-28,变为月末,原30的日期信息丢失
d44 -= boost::gregorian::months(1); //2010-1-31
d44 += boost::gregorian::months(2); //2010-3-31


assert( d44.day() == 31 ); //与原来的日期不相等


//--------------------------
二、日期区间 boost::gregorian::date_period
//--------------------------

1、摘要
它是时间轴上的一个左闭右开区间,端点是两个date对象。区间左值必须小于右值,否则表示一个无效的日期区间


2、构造
一般指定区间的两个端点构造,也可以指定左端点再加上时长构造
boost::gregorian::date_period dp1( boost::gregorian::date(2010,1,1), boost::gregorian::days(20) );
boost::gregorian::date_period dp2( boost::gregorian::date(2010,1,1), boost::gregorian::date(2009,1,1) );//无效
boost::gregorian::date_period dp3( boost::gregorian::date(2010,1,1), boost::gregorian::days(-20) ); //无效


3、日期区间的运算
成员函数shift()、expand()可以变动区间
shift()将日期区间平移n天而长度不变
expand()将日期却向两端延伸n天,相当于区间长度加2n天
原创粉丝点击