Boost库使用----date_time类库

来源:互联网 发布:淘宝主账号不收取信息 编辑:程序博客网 时间:2024/05/17 08:12

Boost库基本功能使用(一)

时间与日期(date_time)

Boost库中使用了timer、date_time、chrono处理时间与日期的问题。在上层开发中,经常碰到不同时间体系的处理,如格里高利历、UTC等,date_time解决了大部分蕾丝的问题,是一个较为全面、灵活的时间和日期类库,并且可以与C的传统时间结构tm相互转换,提供底层支持。

date_time类库简单使用

date_time类库名为libboost_date_time.a
类库包含两个部分,处理日期的gregorian和处理时间的posix_time,在使用时,分别要包含:

// 处理日期组件#include <boost/date_time/gregorian/gregorian.hpp>using namespace boost::gregorian;// 处理时间组件#include <boost/date_time/posix_time/posix_time.hpp>using namespace boost::posix_time;

date_time类库核心类时date类,使用32位整数作为内部存储,时间节点为天;类定义源码可以在/include/boost/date_time中的date.hpp中找到。

创建日期对象

#include <boost/date_time/gregorian/gregorian.hpp>using namespace boost::gregorian;date d1;                    // 无效日期date d2(2017, 9, 1);        // 数字构造date d3(2017, Sep, 1);      // 英文代表月份date d4(d3);                // 拷贝构造// 通过工厂函数d1 = from_string("20170901");d1 = from_undelimited_string("20170901"); // 无分割字符d1 = day_clock::local_day();// 获得本地日期d1 = day_clock::universal_day(); // 获得UTC日期

访问与输出日期

date类成员函数year()、month()、day()分别返回日期的年、月、日;ymd_type year_month_day() 可以一次性获得年月日。输出时一般需要转换为字符串类型,date类不支持直接输出字符串类型,需要使用转换函数,如:

// 输出日期date boostdate = day_clock()::local_day();// 转换为YYYY-MMM-DD格式,其中MMM为英文月份string str1 = to_simple_string(boostdate);// 转换为YYYYMMDD格式的数字字符串string str2 = to_iso_string(boostdate);// 转换为YYYY-MM-DD格式的数字字符串string str3 = to_iso_extended_string(boostdate);

同样,该类兼容底层数据结构,可以与C标准库相互转化:
to_tm(date);
date_from_tm(tm tmdate);

该类简化了很多日期格式的处理方法,还支持日期的长度处理等,更多使用方法可以参考Boost库文档。

原创粉丝点击