【Boost】boost库获取格式化时间

获取时间方式

格式一:YYYYMMDD

#include<iostream>
#include<string>
#include<boost/date_time/gregorian/gregorian.hpp>

using namespace std;

int main(int argc, char* argv)
{
    string strTime = boost::gregorian::to_iso_string(boost::gregorian::day_clock::local_day());
    cout<<strTime<<endl;
    
  //getchar();
return 0; }

输出格式结果

输出格式二:YYYYMMDD-HH:MM:SS

#include<iostream>
#include<string>
#include<boost/date_time/posix_time/posix_time.hpp>

using namespace std;

int main(int argc, char* argv)
{
  
string strPosixTime = boost::posix_time::to_iso_string(boost::posix_time::second_clock::local_time());

     //这时候strPosixTime里存放时间的格式是YYYYMMDDTHHMMSS,日期和时间用大写字母T隔开了,这里是以秒为单元,也可以换成
     //string strPosixTime = boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::local_time());

    int pos = strPosixTime.find('T');    
    strPosixTime.replace(pos,1,std::string("-"));    
    strPosixTime.replace(pos + 3,0,std::string(":"));    
    strPosixTime.replace(pos + 6,0,std::string(":"));    
    cout<<strPosixTime<<endl;
    return 0;
}

输出格式结果

获取时间间隔

 

#include<iostream>
#include<string>
#include<boost/thread.hpp>
#include<boost/date_time/posix_time/posix_time.hpp>

using namespace std;

boost::posix_time::ptime time_now,time_now1;    
boost::posix_time::millisec_posix_time_system_config::time_duration_type time_elapse;    


int main(int argc, char* argv)
{

    // 这里为微秒为单位;这里可以将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_milliseconds(); 

    cout<<time_now<<" "<<time_now1<<endl;
    cout<<time_elapse<<endl;
    cout<<ticks<<endl;
    cout<<sec<<endl;
    

    getchar();
    return 0;
}

 

结果输出

 

posted @ 2018-01-22 13:36  采男孩的小蘑菇  阅读(5699)  评论(0编辑  收藏  举报