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

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

#include <iostream>
#include <chrono>
#include <ctime>
#include <sys/time.h>
#include <cstdint>
constexpr int microSecPerSec = 1000000;
 
int main()
{
    std::chrono::time_point<std::chrono::system_clock> 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<std::chrono::hours>(  //hours
                  p2.time_since_epoch()).count()
                << std::endl;
               
    std::cout << "yesterday, hours since epoch: "
                << std::chrono::duration_cast<std::chrono::hours>(
                  p3.time_since_epoch()).count()
                << std::endl;
             
    std::cout << "Microseconds since epoch: (chrono) : "  //microseconds
                << std::chrono::duration_cast<std::chrono::microseconds>(p2.time_since_epoch()).count() // p2 - p1 ==
                <<std::endl;
               
    std::cout << "Microseconds since epoch: (gettimeofday) :" << mSecond * microSecPerSec + tv.tv_usec
                <<std::endl;
               
    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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1013df99456cf24890d9fa9f79af3680.html