C++11 提供了新的获取系统时间的库函数,在获取时间的时候一般常用的是获取time since epoch,下面来看一下如何获取这个时间。
1 #include <iostream> 2 #include <chrono> 3 #include <ctime> 4 #include <sys/time.h> 5 #include <cstdint> 6 constexpr int microSecPerSec = 1000000; 7 8 int main() 9 { 10 std::chrono::time_point<std::chrono::system_clock> p1, p2, p3; 11 struct timeval tv; 12 int64_t mSecond; 13 14 p2 = std::chrono::system_clock::now(); 15 p3 = p2 - std::chrono::hours(24); 16 gettimeofday(&tv,NULL); 17 mSecond = tv.tv_sec ; 18 19 std::time_t epoch_time = std::chrono::system_clock::to_time_t(p1); // seconds 20 std::cout << "epoch: " << std::ctime(&epoch_time); 21 std::time_t today_time = std::chrono::system_clock::to_time_t(p2); 22 std::cout << "today: " << std::ctime(&today_time); 23 24 std::cout << "hours since epoch: " 25 << std::chrono::duration_cast<std::chrono::hours>( //hours 26 p2.time_since_epoch()).count() 27 << std::endl; 28 29 std::cout << "yesterday, hours since epoch: " 30 << std::chrono::duration_cast<std::chrono::hours>( 31 p3.time_since_epoch()).count() 32 << std::endl; 33 34 std::cout << "Microseconds since epoch: (chrono) : " //microseconds 35 << std::chrono::duration_cast<std::chrono::microseconds>(p2.time_since_epoch()).count() 36 <<std::endl; 37 38 std::cout << "Microseconds since epoch: (gettimeofday) :" << mSecond * microSecPerSec + tv.tv_usec 39 <<std::endl; 40 41 return 0; 42 }
结果:
C:\Users\zhuyp\Desktop\tmp>cpp_time epoch: Thu Jan 01 08:00:00 1970 today: Fri Jan 24 23:51:10 2014 hours since epoch: 386271 yesterday, hours since epoch: 386247 MicroSeconds since epoch: (chrono) : 1390578670080869 Microeconds since epoch: (gettimeofday) :1390578670080869