代码
#include <chrono>
#include <ctime>
#include <string>
#include <iostream>
std::string timp_point()
{
auto high_res_now = std::chrono::high_resolution_clock::now();
// 将高精度时钟的时间点转换为系统时钟的时间点
auto now = std::chrono::time_point_cast<std::chrono::system_clock::duration>(high_res_now);
// 转换为time_t类型
std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
// 转换为本地时间
std::tm *localTime = std::localtime(¤tTime);
// 创建一个缓冲区来存储格式化的日期字符串
char dateBuffer[100];
// 使用strftime格式化日期
std::strftime(dateBuffer, sizeof(dateBuffer), "%Y%m%dT%H%M%S", localTime);
std::string time_p = dateBuffer;
return time_p;
}
int main(){
std::cout << timp_point() << std::endl;
}
常见日志时间
#include <iostream>
#include <chrono>
#include <iomanip>
std::string timp_point() {
auto now = std::chrono::system_clock::now();
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
auto value = now_ms.time_since_epoch().count();
auto us = std::chrono::duration_cast<std::chrono::microseconds>(now - now_ms);
auto us_value = us.count();
// 将时间格式化为字符串
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::tm local_tm = *std::localtime(&now_c);
char dateBuffer[80];
std::strftime(dateBuffer, sizeof(dateBuffer), "%Y-%m-%d %H:%M:%S", &local_tm);
std::ostringstream oss;
oss << dateBuffer << "." << std::setw(6) << std::setfill('0') << us_value;
return oss.str();
}
int main() {
std::cout << timp_point() << std::endl;
return 0;
}
C++获取ms级别时间
#include <iostream>
#include <chrono>
int main() {
// 获取当前时刻的时间点
auto currentTimePoint = std::chrono::high_resolution_clock::now();
// 将时间点转换为毫秒
auto durationInMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTimePoint.time_since_epoch());
// 输出毫秒数
std::cout << "Current time in milliseconds: " << durationInMs.count() << " ms" << std::endl;
return 0;
}