C++如何将文件读取的datetime string转为datetime对象计算时间差
C++ 时间字符串转时间对象及差值计算实现
核心解决思路
你当前代码的核心问题是直接对字符串类型的时间执行减法运算,属于语法错误。需要先将时间字符串解析为可计算的时间对象,再执行差值计算。
前置依赖引入
需要额外引入以下头文件:
#include <chrono> #include <iomanip> #include <sstream>
1. 封装时间字符串解析函数
你的时间格式为YYYY-MM-DD HH:MM:SS,可以用std::get_time完成解析,封装为通用转换函数:
// 定义时间点别名简化代码 using TimePoint = std::chrono::system_clock::time_point; TimePoint str_to_time(const std::string& time_str) { std::tm tm_struct = {}; std::istringstream ss(time_str); // 按匹配格式解析字符串到tm结构体 ss >> std::get_time(&tm_struct, "%Y-%m-%d %H:%M:%S"); // 转换为chrono时间点对象 return std::chrono::system_clock::from_time_t(std::mktime(&tm_struct)); }
2. 修正原有业务代码
你原有代码存在两个问题:
std::string::substr第二个参数是截取长度,不是结束索引while(!MyReadFile.eof())会触发多读空行问题,建议直接用getline返回值作为循环判断条件
修改后的完整逻辑如下:
if (!MyReadFile) { std::cout << "file not found"; } int counter = 0; // 调整map存储结构,同时存时间点和原始字符串按需使用 std::map<std::string, std::pair<std::string, double>> time_records; std::string line; // 修正循环写法 while (std::getline(MyReadFile, line)) { // 修正substr截取参数,第二个参数为时间字符串长度19 std::string start_str = line.substr(6, 19); std::string end_str = line.substr(33, 19); // 转换为时间点对象 TimePoint start_point = str_to_time(start_str); TimePoint end_point = str_to_time(end_str); // 计算毫秒级时间差 double elapsed_ms = std::chrono::duration<double, std::milli>(end_point - start_point).count(); time_records[start_str] = {end_str, elapsed_ms}; counter++; } // 输出结果 for (auto& item : time_records) { std::cout << item.first << ":" << item.second.first << " 耗时:" << item.second.second << "ms" << std::endl; } std::cout << "Frequency is " << counter << std::endl;
效果验证
以你给出的示例行Start: 2021-03-01 09:00:00, Stop: 2021-03-01 14:32:31计算,得到的时间差为19951000ms,即5小时32分31秒,符合预期。
内容的提问来源于stack exchange,提问作者Ch Usman
相关产品推荐
相关产品推荐

