Calculate time difference using c++

669 Views Asked by At

I have a chunk of code where I am trying to convert the string time into time_t and then use the difftime() method to do a comparison. However, currently, the difftime returns 0 instead of the number of seconds differences. Can someone help me on this please.

Here's my C++ code:

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;

I am following this stackoverflow solution as my reference. Really appreciate your helps on this one.

1

There are 1 best solutions below

2
On

Maybe your compiler version is too low.I have no problem compiling the following code in 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 output is the diff is : 7203