现在的位置: 首页 > 综合 > 正文

time_point 的基本用法举例

2013年08月17日 ⁄ 综合 ⁄ 共 1026字 ⁄ 字号 评论关闭

time_point,是C++11引入的表示特定时间点的工具,它工作时需要clock的帮助,可为system_clock, monotonic_clock, 或high_resolution_clock。

time_point在<chrono>头文件中定义,并且使用时要引用 std::chrono命名空间。

其定义形式为 

template< 
    class Clock, 
    class Duration = typename Clock::duration 
> class time_point;

下面是一个使用time_point的小例子,在time_point与C语言中的time相互转换。

#include <ctime>
#include <chrono>
#include <iomanip>
#include <iostream>
using namespace std;
using namespace std::chrono;

int main()
{
    /* 由time_point得到时间点。*/
    time_point<system_clock> now_time = system_clock::now(); //当前时间
    time_t now_c = system_clock::to_time_t(now_time);
    
    tm* now_tm = localtime(&now_c);
    cout << "now : " << put_time(now_tm, "%F %T") << endl;
    // %F - equivalent to "%Y-%m-%d" (the ISO 8601 date format); tm_mon, tm_mday, tm_year
    // %T - equivalent to "%H:%M:%S" (the ISO 8601 time format); tm_hour, tm_min, tm_sec

    /* 如何得到特定时间点的 time_point. */
    tm then_tm;
    then_tm.tm_year = 2012-1900;
    then_tm.tm_mon = 7; //8月
    then_tm.tm_mday = 15;
    then_tm.tm_hour = 19;
    then_tm.tm_min = 19;
    then_tm.tm_sec = 19;

    time_t timetThen = mktime(&then_tm); //得到时间的整数值
    time_point<system_clock> then_tp = system_clock::from_time_t(timetThen);
    //后面就可以使用then_tp了
}

抱歉!评论已关闭.