boost 时间和日期

本文详细介绍了Boost日期时间库的基本使用方法,包括获取本地时间、将字符串转换为时间对象、时间格式化输出以及与其他时间结构的转换等。此外,还探讨了如何处理不同时区的时间转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <boost/date_time.hpp>


1 获取本地时间:
boost::posix_time::second_clock::local_time();  //当前时间

boost::posix_time::microsec_clock::universal_time(); //格林威治时间 和上面的应该是精度不一样
date tod = boost::gregorian::day_clock::local_day(); //当前日期
tod += years(1)  // 加1年.

ptime p(boost::gregorian::date(2012,11,01),hours(1)); // 2012年11月1日 凌晨1点整.




2 把字符串转换为boost 时间类对象:
ptime p1 = from_iso_string("20121101T202020");
ptime p2  = time_from_string("2012-3-5 01:00:00");


3 转换为时间字串:
to_simple_string(ptime);
to_iso_string(ptime);
to_iso_extended_string(ptime);








4 boost时间和其它结构的时间之间的转换


boost::gregorian
std::tm to_tm(const date& d)
date date_from_tm(const std::tm& datetm)


boost::posix_time
ptime from_time_t(std::time_t t)
std::tm to_tm(const boost::posix_time::ptime& t)
std::tm to_tm(const boost::posix_time::time_duration& td) 
ptime ptime_from_tm(const std::tm& timetm) 
TimeT from_ftime(const FileTimeT& ft) ///这个要模版
c_local_adjustor static time_type utc_to_local(const time_type& t)//这个要模版


5 关于时间于时区
boost::gregorian::date today = boost::gregorian::day_clock::universal_day();
boost::local_time::tz_database tz_db;
tz_db.load_from_file("D:\Library\boost_1_51_0\libs\date_time\data\date_time_zonespec.csv");
boost::local_time::time_zone_ptr shz =tz_db.time_zone_from_region("Asia/Shanghai"); //东八区
boost::local_time::time_zone_ptr cst(new boost::local_time::posix_time_zone("CST+08"));//东八区
boost::local_time::local_date_time dt_bj(today,boost::posix_time::hours(12),shz,false);

//ptime 与地区无关. local_time 这个才与地区有关.


//把 东八区上海 时间转换为 utc时间
boost::posix_time::ptime local_to_utc(const boost::posix_time::ptime & local_tm)
{
typedef boost::date_time::local_adjustor< boost::posix_time::ptime, +8, boost::posix_time::no_dst> sct_shz;// 上海 东八区
return sct_shz::local_to_utc(local_tm);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值