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";
The output is:
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 is the converted time_t
not equal to my input date. I would expect that the output is the date expressed in seconds since 1970 (27.05.2010 = 1330905600).
Thanks in advance
mktime
normalizes all its arguments before converting to a time_t
. You have huge values for hour, minute and second, so those are all converted into appropriate numbers of days, pushing the value far into the future.
You need to zero out the other important attributes (including hour/minute/second) of the tm
before calling mktime
. As noted in a comment just initialize it to zero: tm time = {0};
(tagged C++ so the leading struct
isn't needed). Further note that you may wish to set tm_isdst
to -1 so that it attempts to determine the daylight saving value rather than assuming not DST (if initialized to zero).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With