参考链接:
https://en.cppreference.com/w/cpp/chrono/time_point
time_point是c++标准库里的,不需要引入第三方库
使用时需要添加头文件
include
include
time_point其实是一个模板类,工作时需要clock的帮助,可以是system_clock、monotonic_clock、high_resolution_clock
这里使用system_clock
下面的代码简单写了一下使用方法,比较水直接看代码吧
#include "pch.h"
#include <string>
#include <sstream>
#include <iostream>
#include <chrono>
#include <iomanip>
int main()
{
// get current time
std::chrono::time_point<std::chrono::system_clock> nowTime = std::chrono::system_clock::now();
std::time_t tmNowTime = std::chrono::system_clock::to_time_t(nowTime);
std::cout << "nowTimet" << std::put_time(std::localtime(&tmNowTime), "%F %T") << std::endl;
// default_value
std::chrono::time_point<std::chrono::system_clock> startTime;// 1970-1-1 8:0:0;
std::time_t tmStartTime = std::chrono::system_clock::to_time_t(startTime);
std::cout << "startTimet" << std::put_time(std::localtime(&tmStartTime), "%F %T") << std::endl;
// use timestamp
// 2020-01-08 15:05:50(1578466970)
std::chrono::time_point<std::chrono::system_clock> stampTime(std::chrono::seconds(1578466970));
std::time_t tmStampTime = std::chrono::system_clock::to_time_t(stampTime);
std::cout << "stampTimet" << std::put_time(std::localtime(&tmStampTime), "%F %T") << std::endl;
// some hours ago
std::time_t tmSomeTimeAgo = std::chrono::system_clock::to_time_t(nowTime - std::chrono::hours(22) - std::chrono::minutes(30));
std::cout << "22 hours 30 minutes agot" << std::put_time(std::localtime(&tmSomeTimeAgo), "%F %T") << std::endl;
// get time from string
// use "std::get_time()"
std::tm aTime;
std::string strTime("2008-08-08 10:0:0");
std::stringstream ssTime(strTime);
ssTime.imbue(std::locale("de_DE.utf-8"));
ssTime >> std::get_time(&aTime, "%Y-%m-%d %H:%M:%S");
std::chrono::time_point<std::chrono::system_clock> tp = std::chrono::system_clock::from_time_t(std::mktime(&aTime));
std::time_t aTestTime = std::chrono::system_clock::to_time_t(tp);
std::cout << "aTimet" << std::put_time(std::localtime(&aTestTime), "%F %T") << std::endl;
std::cout << "compare: nowTime >= aTime ?t" << (nowTime >= tp ? "true" : "false") << std::endl;
// end time
std::chrono::time_point<std::chrono::system_clock> endTime = std::chrono::system_clock::now();
std::time_t tmEndTime = std::chrono::system_clock::to_time_t(endTime);
std::cout << "endTimet" << std::put_time(std::localtime(&tmEndTime), "%F %T") << std::endl;
std::cout << "the program usedt" << std::chrono::duration_cast<std::chrono::microseconds>(endTime - nowTime).count() << "us.n";
}
从字符串获得time_point的时候借助了stringstream,并且需要知道字符串的对应格式,使用std::get_time函数将字符串转换成std::time_t,再转换成time_pointt
比较时间前后关系也很方便,直接使用>、<、>=、<=、!=、==这种比较运算符就可以
输出结果:
原文链接: https://www.cnblogs.com/Sseakompp/p/12166845.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/191602
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!