boost date_time 下 date的使用

通过查看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);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值