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.
Time difference in C++ // Values via a string
Markus Freitag
3,791
Reputation points
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);
Accepted answer
1 additional answer
Sort by: Most helpful
-
José Pablo Ramirez (a. k. a. webJose) 440 Reputation points
2024-01-08T21:03:34.4333333+00:00 You construct
time1
andtime2
fromtt1
andtt2
. In turn,tt1
andtt2
are constructed withmktime()
usingy1k
andy2k
. In turn,y1k
andy2k
are constructed by converting to number numerical strings from the same variables (strHour
,strMinute
,strSecond
,strYear
,strMonth
andstrDay
). Because of this, the two time values are identical, and their difference is therefore zero.