With the dawn of the new year, and my reflection upon the Clock program I blogged about recently, I’ve been thinking about time. Specifically, the time_t data type used with various C library time functions. Can this value contain negative time?
The time_t value represents the number of seconds ticked in the Unix epoch, since January 1, 1970. As time marches forward, this value increases in a positive direction. Can it be negative? Can you use a time_t value to calculate the date of Caesar’s assassination?
As a review, the following code obtains the current clock-tick value from the time() function, storing it in time_t variable now
. The results are displayed; the ctime() function generates a time-and-date string (with newline), which is output in the code:
#include <stdio.h> #include <time.h> int main() { time_t now; time(&now); printf("It's now %s",ctime(&now)); return(0); }
Here’s sample output, which varies depending on when you run the program:
It's now Sat Jan 05 12:05:23 2019
What about a time_t value of zero? I modified the preceding code to set zero as the time_t value:
#include <stdio.h> #include <time.h> int main() { time_t now = 0; printf("The epoch is %s",ctime(&now)); return(0); }
Here’s the output I saw on my computer:
The epoch is Wed Dec 31 16:00:00 1969
My time zone is -8 hours from UTC, so that explains why the date isn’t midnight, January 1, 1970.
And for a negative value? Here’s my code:
#include <stdio.h> #include <time.h> int main() { time_t now = -63549286400; printf("A bad day for Caesar: %s",ctime(&now)); return(0); }
And the output:
A bad day for Caesar: Thu Mar 15 12:33:42 -044
I’m guessing about the noontime assassination hour, which probably isn’t accurate for time in Italy back in the day. Plus, I had to fiddle with a calculator to get at the exact number of negative seconds before the Unix epoch, but I proved my point: Using C library time functions, you can calculate “negative” dates — and quite far back in time as well.
On my system, the time_t data type is 8-bytes wide, which is a size capable of holding the value 18,446,744,073,709,551,615 or 18 quintillion plus. That’s a lot of time.