date_time库的时间功能位于名字空间boost::posix_time,它提供了微妙级别(最高可达纳秒)的时间系统,使用需要包含头文件"boost\date_time\posix_time\posix_time.hpp"。

1、时间长度类time_duration

  类似日期长度类date_duration有days、weeks、months、years这些常用类,time_duration也有几个子类:hours、minutes、seconds、millisec、microsec、nanosec,他们都支持流输入输出、比较操作、加减乘除运算。

    //对象的定义
    boost::posix_time::time_duration td(1, 10, 30, 1000); //1小时10分钟30秒1毫秒
    boost::posix_time::time_duration  td1(1, 60, 60, 1000); //2小时1分钟1毫秒,超出的时间会自动进位
    boost::posix_time::time_duration td2 = boost::posix_time::duration_from_string("1:10:30:001");  //1小时10分钟30秒1毫秒

    //成员函数
    assert(td.hours() == 1 && td.minutes() == 10 && td.seconds() == 30);
    assert(td.total_seconds() == 1 * 3600 + 10 * 60 + 30);
    
    //获取字符串表示
    cout << boost::posix_time::to_simple_string(td) << endl; //输出为 01:10:30.001000
    cout << boost::posix_time::to_iso_string(td) << endl; //输出为 011030.001000

    //运算
    boost::posix_time::hours h(1);
    boost::posix_time::minutes m(10);
    boost::posix_time::seconds s(30);
    boost::posix_time::millisec ms(1);
    boost::posix_time::time_duration td3 = h + m + s + ms;
    assert(td2 == td3);
View Code

2、时间点ptime

  创建ptime的方法是在其构造函数传入一个date和一个time_duration,不传入time_duration的话为0点,ptime支持流输入输出、比较操作、减法运算、与date_duration、time_duration的加减运算:

    //对象的定义
    boost::posix_time::ptime p(boost::gregorian::date(2010, 3, 5)); //2010年3月5号0点
    boost::posix_time::ptime p1(boost::gregorian::date(2010, 3, 5), boost::posix_time::hours(1)); //2010年3月5号1点
    boost::posix_time::ptime p2 = boost::posix_time::time_from_string("2010-3-5 01:00:00");
    boost::posix_time::ptime p3 = boost::posix_time::from_iso_string("20100505T010000");

    //获取当前时间
    boost::posix_time::ptime p4 = boost::posix_time::second_clock::local_time(); //本地时间,秒精度
    cout << p4 << endl; //可以直接输出ptime,2018-Apr-11 16:23:54
    //boost::posix_time::ptime p4 = boost::posix_time::microsec_clock::local_time(); //本地时间,微妙精度,2018-Apr-11 08:23:54.986535
    //boost::posix_time::ptime p4 = boost::posix_time::second_clock::universal_time(); //UTC时间,微妙精度

    //获取字符串表示
    cout << boost::posix_time::to_iso_extended_string(p) << endl; //输出为2010-03-05T00:00:00
    cout << boost::posix_time::to_iso_string(p) << endl; //输出为20100305T000000
    cout << boost::posix_time::to_simple_string(p) << endl; //输出为2010-Mar-05 00:00:00
View Code

相关文章: