-1

I am having a problem with years in mktime().

Every time I pass a year lower than 1970 into my struct tm and then run the mktime() function to convert my structure, it fails (returns -1).

Does anyone have any idea why and if I can make this work somehow?

alk
  • 69,737
  • 10
  • 105
  • 255
Daeto
  • 440
  • 1
  • 6
  • 19

2 Answers2

7

That is never going to work, since it's by definition outside the epoch, which is the start for Unix time. The manual page states:

The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When interpreted as an absolute time value, it represents the number of seconds elapsed since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).

If it fails to convert the input into Unix time, it's documented to return -1 so that's why you're seeing that result.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Thanks guys, so there is no way around this even on Windows? – Daeto Oct 30 '15 at 15:15
  • Not aware of one, no. There is the concept of a negative value expressing times before the epoch, but that's not supported by `mktime()`. – unwind Oct 30 '15 at 15:17
  • I see, so I would have to use a completely different approach that would not allow me to use the mktime function if I wanted to get the years before 1970 working? – Daeto Oct 30 '15 at 15:56
3

This is expected behavior. Per the man page:

   If the specified broken-down time cannot be represented as calendar
   time (seconds since the Epoch), mktime() returns (time_t) -1 and does
   not alter the members of the broken-down time structure.
Andrew Henle
  • 32,625
  • 3
  • 24
  • 56