Convert struct tm to time_t

I have the following code:

struct tm time; strptime("27052010", "%d%m%Y", &time); cout << "sec: " << time.tm_sec << "\n"; cout << "min: " << time.tm_min << "\n"; cout << "hour: " << time.tm_hour << "\n"; cout << "day: " << time.tm_mday << "\n"; cout << "month: " << (time.tm_mon + 1) << "\n"; cout << "year: " << time.tm_year << "\n"; time_t t = mktime(&time); cout << "sec: " << time.tm_sec << "\n"; cout << "min: " << time.tm_min << "\n"; cout << "hour: " << time.tm_hour << "\n"; cout << "day: " << time.tm_mday << "\n"; cout << "month: " << (time.tm_mon + 1) << "\n"; cout << "year: " << time.tm_year << "\n"; cout << "time: " << t << "\n"; 

Conclusion:

 sec: 1474116832 min: 32767 hour: 4238231 day: 27 month: 5 year: 110 sec: 52 min: 0 hour: 6 day: 2 month: 9 year: 640 time: 18008625652 (Fri, 02 Sep 2540 04:00:52 GMT) 

My question is: why does mktime() change the values ​​of time and why the converted time_t does not match my input date. I expect the exit to be a date, expressed in seconds since 1970 (05/27/2010 = 1330905600).

Thanks in advance

+5
source share
1 answer

mktime normalizes all its arguments before converting to time_t . You have huge values ​​for an hour, minutes and seconds, so they are all converted to the corresponding number of days, increasing the value in the future.

Before calling mktime you need to reset other important attributes (including hour / minute / second) tm . As noted in the comment, just initialize it to zero: tm time = {0}; (C ++ tagged, so leading struct not needed). Please note that you can set tm_isdst to -1 so that it tries to determine the daylight saving time and not assume no DST (if it was initialized to zero).

+6
source

Source: https://habr.com/ru/post/1214744/


All Articles