4

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));
alk
  • 69,737
  • 10
  • 105
  • 255
dcrearer
  • 1,972
  • 4
  • 24
  • 48
  • For me your approach is correct. – Jabberwocky Jan 26 '17 at 06:12
  • @MichaelWalz it's not exactly correct as it uses 365 days per year, in reality the figure is 365.242... – M.M Jan 26 '17 at 06:23
  • Are you assuming a particular epoch? There is the standard unix epoch, but you can use some other epoch if you want. – M.M Jan 26 '17 at 06:24
  • 2
    This is known as the [Year 2038 Problem](https://en.wikipedia.org/wiki/Year_2038_problem). I have a whole talk about it called [REPENT, FOR THE END OF THE UNIX EPOCH IS NIGH](https://www.youtube.com/watch?v=eQFZ_MPTVpc&list=PLftoH6vx4SjkMEmPVG4bBem_vg4F0T7oD&index=1)! (Apologies for the bad audio) – Schwern Jan 26 '17 at 06:37
  • @M.M I wrote _the approach is correct_ and the OP stated that he didn't account for leap years. – Jabberwocky Jan 26 '17 at 06:45

3 Answers3

5

One way would be to use the UNIX date command. Specifically, date -d '@<seconds>' will output the date and time corresponding to <seconds> seconds since the UNIX epoch. Additionally, you can provide the format specifier +%Y if you just care about the year.

So, for this example you would execute

date -d '@2147483647' +%Y

and would see the output 2038.

5

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
alk
  • 69,737
  • 10
  • 105
  • 255
3

The approach may look naive, but is almost accurate. You need to take leap years and maybe leap seconds into account.

The Wikipedia page on UNIX time mentions the year 2038 somewhere. There you find the remaining details.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121