boost::date_time之时间处理

前言:

在日常生活中,关于 日期和时间的处理都很复杂,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;
}

上面运行结果为:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值