我有两个时间戳存储为字符串变量。时间戳的格式为 dd/mm/yyyy-hh:mm:ss 我试图找出两个时间戳之间的秒数差异(忽略日期)。
(我还没有为 a 和 b 分配字符串,但它们每个都有一个时间戳)
对于秒数差异,它总是输出 0,我不明白为什么。
std::string a, b; // hold timestamps
struct tm t, t1;
double seconds;
t.tm_hour = stoi(a.substr(11,2)); // stoi() cast substring to int
t.tm_min = stoi(a.substr(14,2));
t.tm_sec = stoi(a.substr(17,2));
t1.tm_hour = stoi(b.substr(11,2));
t1.tm_min = stoi(b.substr(14,2));
t1.tm_sec = stoi(b.substr(17,2));
seconds = difftime(mktime(&t1), mktime(&t));
std::cout<<seconds;
最佳答案
不要使用硬编码的子字符串值(如果不使用 01 表示法,1 分钟与 11 分钟可能会让您失望...而且您还有月、日和小时要考虑在内)。
不要对偏移量进行硬编码,而是尝试去追踪唯一字符(为了获得“seconds”,只考虑第二次出现“:”之后的字符串)。
关于c++ - 在 C++ 中比较两个时间戳字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22568343/