利用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;
- #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());
-
-
- 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;
- #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());
-
-
- 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;
-
- time_now = boost::posix_time::microsec_clock::universal_time();
-
- boost::this_thread::sleep(boost::posix_time::millisec(100));
-
- time_now1 = boost::posix_time::microsec_clock::universal_time();
-
- time_elapse = time_now1 - time_now;
-
- int ticks = time_elapse.ticks();
-
- int sec = time_elapse.total_seconds();
- #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;
-
- time_now = boost::posix_time::microsec_clock::universal_time();
-
- boost::this_thread::sleep(boost::posix_time::millisec(100));
-
- time_now1 = boost::posix_time::microsec_clock::universal_time();
-
- time_elapse = time_now1 - time_now;
-
- int ticks = time_elapse.ticks();
-