栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

利用boost获取时间并格式化的方法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

利用boost获取时间并格式化的方法

利用boost来获取当前时间又方便快捷,还不用考虑跨平台的问题。

1.   输出YYYYMMDD

#include  
#define BOOST_DATE_TIME_SOURCE 
   
std::string strTime = boost::gregorian::to_iso_string( 
boost::gregorian::day_clock::local_day()); 
   
std::cout << strTime.c_str() << std::endl;

2.   输出YYYYMMDD-HH:MM:SS

#include  
#define BOOST_DATE_TIME_SOURCE 
   
std::string strTime = boost::posix_time::to_iso_string( 
boost::posix_time::second_clock::local_time()); 
   
// 这时候strTime里存放时间的格式是YYYYMMDDTHHMMSS,日期和时间用大写字母T隔开了 
   
int pos = strTime.find('T'); 
strTime.replace(pos,1,std::string("-")); 
strTime.replace(pos + 3,0,std::string(":")); 
strTime.replace(pos + 6,0,std::string(":")); 
   
std::cout << strTime.c_str() << std::endl; 

3.   计算时间间隔。boost里计算时间间隔的功能很多很强大,我列举的仅仅是我目前用到的。

#include  
#include  
#define BOOST_DATE_TIME_SOURCE 
 
boost::posix_time::ptime time_now,time_now1; 
boost::posix_time::millisec_posix_time_system_config::time_duration_type time_elapse; 
 
// 这里为微秒为单位;这里可以将microsec_clock替换成second_clock以秒为单位; 
time_now = boost::posix_time::microsec_clock::universal_time(); 
 
// sleep 100毫秒; 
boost::this_thread::sleep(boost::posix_time::millisec(100)); 
 
time_now1 = boost::posix_time::microsec_clock::universal_time(); 
 
time_elapse = time_now1 - time_now; 
 
// 类似GetTickCount,只是这边得到的是2个时间的ticket值的差,以微秒为单位; 
int ticks = time_elapse.ticks(); 
 
// 得到两个时间间隔的秒数; 
int sec = time_elapse.total_seconds(); 

以上这篇利用boost获取时间并格式化的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/63813.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号