通过查看gregrorian目录下可以看到许多关于时间处理的源文件。
date_time 库支持无限时间与无效时间等概念。
date_time 支持1400-01-01 到9999-12-31之间的日期计算。
该库位于命名空间下的grepgorian 中,使用必须包含头文件#include<boost/date_time/gregorian/gregorian.hpp>
使用using namespace boost::grepforian;
可查看boost_1_58_0/boost/date_time/gregorian下的源码。
例子:
#include<iostream>
#include<unistd.h>
#include<boost/date_time/gregorian/gregorian.hpp>
using namespace boost::gregorian;
using namespace std;
int main(void)
{
date d; //无效的对象
date d1(2017,12,21);//使用数字构造对象
date d2(2000,Jan,2);//也可使用英文构造
assert(d1==d2);//支持对象的比较
assert(d1<d2);
assert(d1.year()==2017);
cout<<d1<<endl;
//date支持字符串产生
date d4=form_string("2017-12-31");
date d5(form_string("2017/12/21"));
date d6=form_undelimited_string("20171221");
cout<<day_clock::local_day()<<endl;//返回当天日期
cout<<day_colck::universal_day()<<endl;//返回当天日期的对象
date d7(neg_infin);//负无限日期
date d8(pos_infin);//正无限日期
date d9(not_a_date_time);//无效日期
date d10(max_date_time);//最大可用日期
date d11(min_date_time);//最小可用日期
//成员函数 year() month() day()分别返回日期的年 月 日
assert(d1.year()==2017);
assert(d1.month()==12);
assert(d1.day()==21);
//year_month_day() 返回一个 ymd_type 结构 可以一次性获取年月日
date::ymd_type ymd=d1.year_month_day();
assert(ymd.year==2017);
assert(ymd.month=12);
assert(ymd.day=21);
//成员函数day_of_week() 返回date的星期数 day_of_year() 返回当年的第几天
//end_of_month()返回当月的最后一天的date对象
assert(d1.day_of_week()==4);
assert(d1.day_of_year()==345);
assert(d1.end_of_month()==date(2017,12,31));
///
//支持YYYY-mmm-dd YYYYmmdd 输出
cout<<to_iso_extended_string(d1)<<endl;
cout<<to_iso_string(d1)<<endl;
cout<<to_simple_string(d1)<<endl;
//支持与CSTL tm结构的转换
tm t=to_tm(d1);
assert(t.tm_hour==0&&t.tm_min==0);
assert(t.tm_year==2010 && t.tm_mday==1);
date d13=date_from_tm(t);
assert(d13==d1);
return 0;
}
//日期长度 date_duration 可查看date_time目录下的date_duration.hpp文件
//days months years weeks
days dd1(10),dd2(-100),dd3(255);
assert(dd1>dd2 && dd1<dd3);
assert(dd1+dd2==days(-90));
assert((dd1+dd3).days()==265);
assert(dd3/5==days(51));
weeks w(3);//3星期
assert(w.days()==21);
months m(5);//5个月
years y(2);//2年
//支持四则运算
months m2=y+m;
assert(m2.number_of_months()==29);
assert((y*2).number_of_year()==4);