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了}
复制代码
评论