1

I prepare the following structure :

struct tm tDepartureTime;
tDepartureTime.tm_min = 24;
tDepartureTime.tm_hour = 13;
tDepartureTime.tm_mday = 11;
tDepartureTime.tm_mon = 2 - 1;
tDepartureTime.tm_year = 2017 - 1900;

then I use mktime() to get the number of seconds.

unsigned long qTime = mktime( &tDepartureTime );

but it returns me number 1731157832 which is timestamp equivalent for 09.11.2024. Where could be a problem?

3
  • Did you intend the date to be in February 2017? (The values of tm_mon run from 0 for January to 11 for December.) Commented Dec 16, 2016 at 21:47
  • @JonathanLeffler, yes Jonathan, it was intended for February. Anyway thank you for notify me.
    – user3053231
    Commented Dec 18, 2016 at 15:34
  • OK. Since you wrote 2017 - 1900 but didn't write 2 - 1 I wasn't sure, but it didn't materially affect your question Commented Dec 18, 2016 at 15:37

1 Answer 1

3

Some fields of your tm structure are uninitialized. Specifically, these are tm_sec, tm_mday, tm_wday, tm_yday and tm_isdst.

Of these, you need to manually set, at the very least, tm_sec. If its value randomly ends up being very high, that explains the time far into the future.

You could also initialize the entire struct with zeroes by changing your first line into struct tm tDepartureTime = {0}. This is probably the best solution.

1
  • The values of tm_wday, tm_yday don't matter and are set as a side-effect of calling mktime(). The value was set for tm_mday. As you correctly said, the value in tm_sec was not set and the value actually present was probably quite large. Commented Dec 16, 2016 at 21:49