Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 919
dcrearer Avatar asked Dec 10 '22 13:12

dcrearer


2 Answers

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
like image 64
alk Avatar answered May 15 '23 19:05

alk


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.

like image 22
Brett Boston Avatar answered May 15 '23 19:05

Brett Boston