Boost库使用----date_time类库

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库文档。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值