經過一段時間的執行,我們經常需要實現程序的功能。如果您使用boost,它可以通過多種方式實現,那么boost獲取時間并格式化的方法有哪些?武林技術頻道小編將和大家分享。
1.? ?輸出YYYYMMDD
#include <boost/date_time/gregorian/gregorian.hpp> #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 <boost/date_time/posix_time/posix_time.hpp> #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 <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread.hpp> #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獲取時間和格式的方法是編輯器共享所有的內容,希望能給您一個參考,同時也希望您能支持更多的Vevb技術頻道。
新聞熱點
疑難解答
圖片精選