前言:
在日常生活中,关于 日期和时间的处理都很复杂,date_time库有很多工具来简化工作,比如日期、时间迭代器以指定的时间间隔来遍历时间,boost::posix_time库能获取系统当前具体的时间,可以把时间和c语音内置的ts结构体相互转化,根据需要转化时间电脑格式和已经不同初始化时间的方法,boost的date_time库都为我们做了很多。
虽然date_time不能处理1400年前的日期,因此无法用它来研究那之前的历史。但总的来说date_time的贡献是巨大的,它赋予了我们自由处理时间的能力,值得我们学习
简单实现:
#include "stdafx.h"
#include <iostream>
#include "boost/date_time/gregorian/gregorian.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/local_time/local_time.hpp"
#include <iostream>
#include <locale>
using namespace std;
int main() {
using namespace boost::gregorian;
using namespace boost::posix_time;
using namespace boost::local_time;
boost::gregorian::date d(neg_infin);
cout << "neg_infin = "<< d << endl;
date dd(max_date_time);
cout << "最大可能时间 = "<< dd << endl;
date ddd(min_date_time);
cout << "最小可能时间 = "<< ddd << endl;
//构造时间时超过最大或小于最小时间都会抛出异常
date d2(2015,3,4);
cout << "初始化时间 = "<< d2 << endl;
string strForDate = to_simple_string(d2);
cout << "转换成字符串(格式为YYYY-mmm-DD): " << strForDate << endl;
strForDate = to_iso_string(d2);
cout << "转换成字符串(格式为YYYYMMDD,其中mmm为3字符英文月份名): " << strForDate << endl;
strForDate = to_iso_extended_string(d2);
cout << "转换成字符串(格式为YYYY-MM-DD): " << strForDate << endl;
cout << "初始化时间年:" << d2.year() << " 月:" << d2.month() << " 天:" << d2.day() << endl;
cout << "距离今年年初已经过去 " << d2.week_number() << " 周"<< endl;
date d3(2016,3,4);
cout << "d3与d2时间天数差为(会计算上当天的时间):" << d3 - d2 << endl;
cout << "d3=" << d3 << " d3加上10天:" << d3 + days(10) << endl;
//获取系统当前日期:
std::string strLocalDate = boost::gregorian::to_iso_extended_string( boost::gregorian::day_clock::local_day() );
cout << "系统当前日期为" << strLocalDate << endl;
//获取当前具体时间:
std::string strLocalTime = boost::posix_time::to_iso_extended_string(boost::posix_time::second_clock::local_time());
cout << "系统当前时间为" << strLocalTime << endl;
std::locale loc(std::locale::classic(), timefacet);
while(1)
{
;
}
return 0;
}
上面运行结果为: