0

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.

  • Works for me: https://godbolt.org/z/Gr58Yh86E – paddy Apr 27 '21 at 03:00
  • Kind of related: [Getting an accurate execution time in C++ (micro seconds)](https://stackoverflow.com/questions/21856025/getting-an-accurate-execution-time-in-c-micro-seconds) – Gabriel Staples Apr 27 '21 at 03:22

1 Answers1

0

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

Lintong He
  • 109
  • 4