Time difference in C++ // Values via a string

Markus Freitag 3,791 Reputation points
2024-01-08T17:56:21.5633333+00:00

Hello,

I would like to calculate the time difference from a string. How can I best solve this?

Is not working, why?

return value in seconds or ms.

time_t timer;
struct tm y2k; // = { 0,0,0,0,0,0,0,0,0 };
double seconds;

string strHour = "19";
string strMinute = "05";
string strSecond = "44";
string strYear = "2024";
string strMonth = "01";
string strDay = "8";

y2k.tm_hour = atoi(strHour.c_str());
y2k.tm_min = atoi(strMinute.c_str());
y2k.tm_sec = atoi(strSecond.c_str());
y2k.tm_year = atoi(strYear.c_str());
y2k.tm_mon = atoi(strMonth.c_str());
y2k.tm_mday = atoi(strDay.c_str());

time(&timer);  /* get current time; same as: timer = time(NULL)  */

seconds = difftime(timer, mktime(&y2k));

struct tm y1k; // = { 0,0,0,0,0,0,0,0,0 };

y1k.tm_hour = atoi(strHour.c_str());
y1k.tm_min = atoi(strMinute.c_str());
y1k.tm_sec = atoi(strSecond.c_str()) - 2;
y1k.tm_year = atoi(strYear.c_str());
y1k.tm_mon = atoi(strMonth.c_str());
y1k.tm_mday = atoi(strDay.c_str());

time_t tt1, tt2;
tt1 = mktime(&y1k);
tt2 = mktime(&y2k);

CTime time1(tt1), time2(tt2);
CTimeSpan ts = time2 - time1;

//int se = tt2 - tt1;

//double seconds5 = difftime(tt2, tt1);
seconds = difftime(tt2, tt1);


//printf("%.f seconds since January 1, 2000 in the current timezone", seconds);
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,853 questions
{count} votes

Accepted answer
  1. Barry Schwarz 3,331 Reputation points
    2024-01-09T00:23:23.6433333+00:00

    Look up the definition of struct_tm. You are setting one of the variables in y2k incorrectly causing mktime to return -1 instead of the value you are expecting. You would have spotted this immediately if you had stepped through the program in the debugger.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. José Pablo Ramirez (a. k. a. webJose) 440 Reputation points
    2024-01-08T21:03:34.4333333+00:00

    You construct time1 and time2 from tt1 and tt2. In turn, tt1 and tt2 are constructed with mktime() using y1k and y2k. In turn, y1k and y2k are constructed by converting to number numerical strings from the same variables (strHour, strMinute, strSecond, strYear, strMonth and strDay). Because of this, the two time values are identical, and their difference is therefore zero.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.