chrono程序库定义了一系列关于时间和日期的操作接口,是自C++11之后提供的标准库文件,定义于chrono文件中,使用时需要包含其头文件。
获取系统当前时间可以使用system_clock()中的now()接口,然后使用to_time_t()将其转换为C风格的时间类型time_t,time_t实际是long long类型。然后使用ctime()接口,将其转换为日历表示法,更加容易识别。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
int main()
{
// 使用C++中的chrono程序库获取系统当前时间
chrono::system_clock::time_point tp = chrono::system_clock().now();
// 转换为C风格的时间类型time_t
time_t tm = chrono::system_clock::to_time_t(tp);
// 使用ctime()接口将时间转换为日历表示法,string类型
string ts = ctime(&tm);
// 移除末尾换行符
ts.resize(ts.size() - 1);
// 输出结果:当前时间
cout << ts;
return 0;
}
当前输出:
Tue Jun 16 08:13:33 2020
谢谢阅读