c++ - 在 C++ 中比较两个时间戳字符串

标签 c++ difference

我有两个时间戳存储为字符串变量。时间戳的格式为 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/

相关文章:

c++ - 在托管 C++ 类库中使用 System::Drawing 命名空间

c++ - 从连续的单词序列中提取任意范围的位的最有效方法是什么?

c++ - 数组 :/有问题

c++ - 增加字符串中的数字

javascript - 计算当前日期与另一个日期之间的差异时出现错误

使用抽象接口(interface)的 C++ Dll 边界 -> header 中的智能指针?调用删除?

python - Pandas : difference() methode between polygon and points

javascript - 使用javascript获取两个字符串之间的日差

google-apps-script - 比较列中的代码后查找两个工作表之间的差异行

image - CV - 提取两个图像之间的差异