Use boost to get the time and format the method
- 2020-05-17 06:02:06
- OfStack
Using boost to get the current time is convenient and quick, without considering cross-platform issues.
1. Output 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. Output 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());
// At this time strTime The format of storage time is YYYYMMDDTHHMMSS Date and time in capital letters T Separated from the
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. Calculate the time interval. There are many powerful functions in boost for calculating time intervals, but I have listed only those I have used so far.
#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;
// This is in microseconds ; You can put microsec_clock replace second_clock In seconds ;
time_now = boost::posix_time::microsec_clock::universal_time();
// sleep 100 ms ;
boost::this_thread::sleep(boost::posix_time::millisec(100));
time_now1 = boost::posix_time::microsec_clock::universal_time();
time_elapse = time_now1 - time_now;
// similar GetTickCount It's just that what you get over here is 2 A time of ticket The difference in microseconds ;
int ticks = time_elapse.ticks();
// You get the number of seconds between the two intervals ;
int sec = time_elapse.total_seconds();