使用 C++ 计算时差

问题描述

我有一段代码,我试图将字符串时间转换为 time_t,然后使用 difftime() 方法进行比较。但是,目前,difftime 返回 0 而不是秒数差异。有人可以帮助我吗。

这是我的 C++ 代码

const char *time_details = "16:35:12";
const char *another_time = "18:35:15";
struct tm tm = { 0 };
struct tm tm1 = { 0 };
istringstream ss(time_details);
istringstream ss1(another_time);
ss >> get_time(&tm,"%H:%M:%s"); // or just %T in this case
ss1 >> get_time(&tm1,"%H:%M:%s");
std::time_t time1 = mktime(&tm);
std::time_t time2 = mktime(&tm1);
double a = difftime(time2,time1);
cout << "the diff is : " << a;

我正在关注 this stackoverflow 解决方案作为我的参考。非常感谢您在这方面的帮助。

解决方法

可能你的编译器版本太低了。我用g++ 9编译下面的代码没有问题。

#include <ctime>
#include <sstream>
#include <iomanip> 
#include <time.h>
#include <iostream>

using namespace std;

int main()
{
    const char *time_details = "16:35:12";
    const char *another_time = "18:35:15";
    struct tm tm = { 0 };
    struct tm tm1 = { 0 };
    istringstream ss(time_details);
    istringstream ss1(another_time);
    ss >> get_time(&tm,"%H:%M:%S"); // or just %T in this case
    ss1 >> get_time(&tm1,"%H:%M:%S");
    std::time_t time1 = mktime(&tm);
    std::time_t time2 = mktime(&tm1);
    double a = difftime(time2,time1);
    cout << "the diff is : " << a;
    return 0;
}

输出为the diff is : 7203