cunixtime-tyear2038

calendar time stored as a signed 32-bit integer - when will it overflow


I'm going through exercises from Advanced Programming in Unix and encountered the following question:

If the calendar time is stored as a signed 32-bit integer, in which year will it overflow?

positive signed integer = 2147483647

In the following calculation I'm not accounting for leap years:

((((2147483647 / 60sec) /60min)/24)/365) = 68.1yrs

This is a naive approach. How can I approach this question professionally?

The following solution presented earlier by a stack member was very helpful to print out the year.

int epoch_time = INT_MAX;
struct tm * timeinfo;
time_t epoch_time_as_time_t = epoch_time;
timeinfo = localtime(&epoch_time_as_time_t);
printf("2] overflow date: %s", asctime(timeinfo));

Solution

  • when will it overflow

    Assuming that on the platform in question int is 32 bits wide (and time_t is an integral type, will say it's not a struct for example), just do

    printf("%s\n", asctime(localtime(&(time_t){difftime(INT_MAX, 0)})));
    

    and you know.

    It prints:

    Tue Jan 19 04:14:07 2038
    

    Exchanging the arguments to difftime() one gets the "earliest" date possible, BTW:

    printf("%s\n", asctime(localtime(&(time_t){difftime(0, INT_MAX)})));
    

    prints

    Fri Dec 13 21:45:53 1901