C++11 获取系统时间库函数 time since epoch

C++11 提供了新的获取系统时间的库函数,在获取时间的时候一般常用的是获取time since epoch,下面来看一下如何获取这个时间。

#include
#include
#include
#include
#include
constexpr int microSecPerSec = 1000000;
 
int main()
{
    std::chrono::time_point p1, p2, p3;
    struct timeval tv;
    int64_t mSecond;
 
    p2 = std::chrono::system_clock::now();
    p3 = p2 - std::chrono::hours(24);
    gettimeofday(&tv,NULL);
    mSecond = tv.tv_sec ;
 
    std::time_t epoch_time = std::chrono::system_clock::to_time_t(p1); // seconds
    std::cout << "epoch: " << std::ctime(&epoch_time);
    std::time_t today_time = std::chrono::system_clock::to_time_t(p2);
    std::cout << "today: " << std::ctime(&today_time);
 
    std::cout << "hours since epoch: "
                << std::chrono::duration_cast(  //hours
                  p2.time_since_epoch()).count() 
                << std::endl;
                
    std::cout << "yesterday, hours since epoch: "
                << std::chrono::duration_cast(
                  p3.time_since_epoch()).count() 
                << std::endl;
              
    std::cout << "Microseconds since epoch: (chrono) : "  //microseconds
                << std::chrono::duration_cast(p2.time_since_epoch()).count() // p2 - p1 ==
                <                 
    std::cout << "Microseconds since epoch: (gettimeofday) :" << mSecond * microSecPerSec + tv.tv_usec 
                <                 
    return 0;
}

结果:

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
Microseconds since epoch: (gettimeofday) :1390578670080869

你可能感兴趣的:(STL)