0

I am dealing with timestamps generated by a system where the epoch is not the standard UNIX epoch of seconds since midnight of Jan 1, 1970 (it starts somewhere in 1965 instead). This question is kind of related. So, I have a "fixup" function to deal with this offset:

time_t fix_time(uint32_t raw_time)
{
    const int32_t epoch_offset = 157680000; /* offset wrt UNIX epoch */
    time_t fixedTime = static_cast<time_t>(raw_time - epoch_offset);
    return fixedTime;
}

and continue using the standard library functions in rest of the code:

uint32_t raw_time;
time_t timestamp = fix_timestamp(raw_time);
struct tm timeinfo;
gmtime_r(&timestamp, &timeinfo);

It seems to work as intended (held up to a mix of real and synthetic test data, so far). However, is there a better way to deal with this scenario? Are there any subtle ways in which this might break? Additional info if it matters: the timestamps are spread out over 1981 to the current day and the program runs on a Linux machine.

Community
  • 1
  • 1
Bhargav
  • 9,869
  • 1
  • 19
  • 29
  • The `` is unnecessary; since both `int32_t` and `time_t` are arithmetic types, the conversion is done implicitly. – Keith Thompson Mar 23 '15 at 05:38
  • Thanks for the input, I generally tend to do that as a note to myself (and others) reading the code that the casting is intentional. – Bhargav Mar 23 '15 at 06:19
  • 1
    @BhargavBhat: it can suppress compiler warnings when converting to a type that can't store all the original values, whether due to using less bytes or being signed or unsigned. More generally, 32 bit values storing date/times in the UNIX Epoch will wrap in 2038 - you've chopped off an extra ~5 years - so should be right until about 2033. – Tony Delroy Mar 23 '15 at 06:47
  • 1
    @TonyD: yup, that seems right. One of the synthetic dates I used was pretty close to UINT32_MAX and I got a date somewhere in November 2033. – Bhargav Mar 23 '15 at 07:29

1 Answers1

0

time_t is already a C legacy. For your own time, you should really make a class. The main advantage of such a class is that you can avoid unintended behavior. You define which operators make sense, and operator^ probably does not. You define which conversions are supported, and that's probably just to time_t (if at all - the alternative is a .getCtime() method)

Internally, you can use an unsigned long which gives you at least 68 years extra. The Y2038 problem is because time_t is signed, and the UNIX era runs from 1902 to 2038.

MSalters
  • 173,980
  • 10
  • 155
  • 350