c++的时间点time_point基本⽤法
参考链接:
time_point是c++标准库⾥的,不需要引⼊第三⽅库
使⽤时需要添加头⽂件
#include <chrono>
#include <iomanip>
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 << "nowTime\t" << 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 << "startTime\t" << std::put_time(std::localtime(&tmStartTime), "%F %T") << std::endl;
// use timestamp
// 2020-01-08 15:05:50(1578466970)
system的头文件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 << "stampTime\t" << 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 ago\t" << 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 << "aTime\t" << 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 << "endTime\t" << std::put_time(std::localtime(&tmEndTime), "%F %T") << std::endl;
std::cout << "the program used\t" << std::chrono::duration_cast<std::chrono::microseconds>(endTime - nowTime).count() << "us.\n";
}
从字符串获得time_point的时候借助了stringstream,并且需要知道字符串的对应格式,使⽤std::get_time函数将字符串转换成std::time_t,再转换成time_pointt
⽐较时间前后关系也很⽅便,直接使⽤>、<、>=、<=、!=、==这种⽐较运算符就可以输出结果:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论