BOOST DATE_TIME
boost的时间库分在两个文件和命名空间里
<boost/date_time/posix_time/posix_time.hpp> boost::_posix_time
<boost/date_time/gregorian/gregorian.hpp> boost::gregorian
前者是时间日期类ptime和timeduration类,后者是日期类date和date_duration类
时间和日期的应用中概念重要是三种ptime代表一个整体的日间和日期、date代表日期类、timeduration主要代表时间跨度类、date_duration代表日期跨度类
获取当期日期和当前时间日期
//获取当前时间日期
boost::posix_time::ptime p(boost::posix_time::second_clock::local_time()); //精确到秒
boost::posix_time::ptime p(boost::date_time::microsec_clock<boost::posix_time::ptime>::local_time()); //精确到微妙
//获取当前日期
boost::gregorian::day_clock::local_day(); //精确到天
构造
日期的构造
include <boost/date_time/gregorian/gregorian.hpp>
boost::gregorian::date d(2015, 1, 1);
boost::gregorian::from_string("2015-01-01");
boost::gregorian::from_undelimited_string("20150101");
to_iso_string(date d); // return "20020131"
to_iso_extended_string(date d); // return "2002-01-31"
时间日期的构造
time_duration类有5个子类,hours,minutes,seconds,millisec,nanosec,他们之间做加减依然是time_duration
#include <boost/date_time/posix_time/posix_time.hpp>
date d;
time_duration td
boost::posix_time::ptime p(d,td); //由date和time_duration构造
boost::posix_time::ptime p(boost::posix_time::time_from_string("2012-01-02 10:00:00.000000")) //由字符串构造
时间算术
time_duration类有5个子类,hours,minutes,seconds,millisec,nanosec,他们之间做加减依然是time_duration
date_duration类有months、weeks、years三个子类、date_duration类本身代表天
date类加减形成date_duration类
ptime类加减形成time_duration类
ptime类还可以加减date_duration类
时间、字符串、数字之间的转换
string-------->日期、时间日期
boost::posix_time::ptime p(boost::posix_time::time_from_string("2012-01-02 10:00:00.000000")) //由字符串构造
boost::gregorian::from_string("2015-01-01");
boost::gregorian::from_undelimited_string("20150101");
日期、时间日期------------>字符串 这里无法直接控制格式建议需要控制格式时先转换为整数,再由整数转换为字符串
to_iso_string(date d); // return "20020131"
to_iso_extended_string(date d); // return "2002-01-31"
to_simple_string(ptime p); // return "2002-Jan-01 10:00:01.123456789"
数字----------->日期、时间日期
date d(2015, 1, 1);
time_duration td = hours(1) + minutes(1) + seconds(2) + millisec(50);
ptime p(d, td);
日期、时间日期------------->数字
date d;
d.year();
d.month();
d.day();
p.date().year();
p.date().month();
p.date().day();
p.time_of_day().hours();
p.time_of_day().minutes();
p.time_of_day().seconds();
p.time_of_day().fractional_seconds(); //fractional_seconds 默认是微妙
时间输出格式化
时间输出格式化非常麻烦,这里给出参考链接
http://www.boost.org/doc/libs/1_64_0/doc/html/date_time/date_time_io.html