boost完全开发指南第2章-处理时间3(日期date)

来源:互联网 发布:acca知乎 编辑:程序博客网 时间:2024/05/18 01:10

5、date

(1)创建日期

测试代码:

#include <iostream>#include <boost/date_time/gregorian/gregorian.hpp>using namespaceboost::gregorian; void create_date_obj_test(){   date d1;   date d2(2010,1,1);   date d3(2013,Dec, 3);   date d4(d2);    assert(d1==date(not_a_date_time));   assert(d2!=d3);   assert(d2<d3);   //from string   date d5= from_string("2013-12-3");   date d6(from_string("2013/12/3"));   date d7= from_undelimited_string("20131203");   assert(d5==d6);   assert(d6==d7);    cout<<day_clock::local_day()<<endl;   cout<<day_clock::universal_day()<<endl;} 


(2)访问日期

测试代码:

#include <iostream>#include <boost/date_time/gregorian/gregorian.hpp>using namespaceboost::gregorian; void access_date_test(){   date dt(2013,12,3);   cout<<dt.year()<<"-"<<dt.month()<<"-"<<dt.day()<<endl;   date::ymd_typeymd =dt.year_month_day();   cout<<"year="<<ymd.year<<endl;   cout<<"month="<<ymd.month<<endl;   cout<<"day="<<ymd.day<<endl;    cout<<"day_of_week:"<<dt.day_of_week()<<endl;   cout<<"day_of_year:"<<dt.day_of_year()<<endl;   cout<<"end_of_month:"<<dt.end_of_month()<<endl;}

(3)日期的输出

测试代码:

#include <iostream>#include <string>#include <boost/date_time/gregorian/gregorian.hpp> using namespacestd;using namespaceboost::gregorian; void format_date_string_test(){   date dt(2013,12,3);   //to_simple_string   std::stringsimple_str =to_simple_string(dt);   cout<<"to_simple_string:"<<simple_str<<endl;   //to_iso_string   string iso_str= to_iso_string(dt);   cout<<"to_iso_string:"<<iso_str<<endl;   //to_iso_extended_string   string iso_extend_str= to_iso_extended_string(dt);   cout<<"to_iso_extended_string:"<<iso_extend_str<<endl;}

(4)与tm转换

void convert_to_tm_test(){date d(2013,12,3);tm t = to_tm(d);cout<<"tm.year: "<<t.tm_year<<" tm.month:"<<t.tm_mon<<" tm.day:"<<t.tm_mday<<endl;date d_ = date_from_tm(t);cout<<d_<<endl;}


(5)日期长度

date_duration, days, months, weeks,

 

测试代码:

#include <iostream>#include <string>#include <boost/date_time/gregorian/gregorian.hpp>using namespace std;using namespace boost::gregorian;void date_duration_test(){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);assert(w.days()==21);months m(2);years y(1);months m2= y+m;assert(m2.number_of_months()==14);assert((y*2).number_of_years()==2);}


(6)日期运算

测试代码:

void date_calculate_test(){date d1(2012,1,1), d2(2013,1,8);cout<<"d1: "<<d1<<" , d2: "<<d2<<endl;cout<<"d2-d1:"<<d2-d1<<endl;d1+=days(10);cout<<"d1+=days(10): "<<d1.day()<<endl;d1+=months(2);cout<<"d1+=months(2) "<<d1.month()<<endl;d1+=years(1);cout<<"d1+=years(1) "<<d1.year()<<endl;//d2cout<<"d2-1week:";d2-=weeks(1);cout<<d2.day_of_week()<<","<<d2.week_number()<<endl;}


 

0 0
原创粉丝点击