time_t
The most basic representation of a date and time is the type time_t. The value of a time_t variable is the number of seconds since January 1, 1970, sometimes call the Unix epoch. This is the best way to internally represent the start and end times for an event because it is easy to compare these values. Two time_t values a and b can be compared using <:
if(a < b) { printf("Time a is before time b "); }
struct tm
While time_t represents a date and time as a single number, struct tm represents it as a struct with a lot of numbers:
struct tm { int tm_sec; /* Seconds. [0-60] (1 leap second) */ int tm_min; /* Minutes. [0-59] */ int tm_hour; /* Hours. [0-23] */ int tm_mday; /* Day. [1-31] */ int tm_mon; /* Month. [0-11] */ int tm_year; /* Year - 1900. */ int tm_wday; /* Day of week. [0-6] */ int tm_yday; /* Days in year.[0-365] */ int tm_isdst; /* DST. [-1/0/1]*/ };
Conversion
You can convert a time_t value to a struct tm value using the localtime function:
struct tm startTM; time_t start; /* ... */ startTM = *localtime(&start);
You can convert a struct tm value to a time_t value using the mktime function:
struct tm startTM; time_t start; /* ... */ start = mktime(&startTM);
How to input a date
Your program will need to input a date. Here is an example of a safe and robust way to input a date:
time_t InputDate(char *prompt) { char buffer[100]; char *result; struct tm date; do { printf("%s", prompt); /* Get a line of up to 100 characters */ fgets(buffer, sizeof(buffer), stdin); /* Remove any we may have input */ if(strlen(buffer) > 0) buffer[strlen(buffer)-1] = '