How to Work with Time in C Programming - dummies

How to Work with Time in C Programming

By Dan Gookin

Time functions and related matters in the C programming language are contained in the time.h header file. In this file, you find the goodies described in this list:

  • time_t: The time_t variable type holds the value of the Unix epoch, or the number of seconds that have passed since January 1, 1970. On most systems, time_t is a long signed int converted into time_t by the typedef keyword. Because of the 2038 issue, it may be an unsigned or another variable type on your system.

  • struct tm: This structure holds definitions for storing various parts of a timestamp. It’s filled by the localtime() function. Here’s approximately how the structure looks, though on your system it may be different:

    struct tm {
     int tm_sec; /* seconds after the minute [0-60] */
     int tm_min; /* minutes after the hour [0-59] */
     int tm_hour; /* hours since midnight [0-23] */
     int tm_mday; /* day of the month [1-31] */
     int tm_mon; /* months since January [0-11] */
     int tm_year; /* years since 1900 */
     int tm_wday; /* days since Sunday [0-6] */
     int tm_yday; /* days since January 1 [0-365] */
     int tm_isdst; /* Daylight Saving Time flag */
  • time(): The time() function eats the address of the time_t variable and fills that variable with the current Unix epoch time — basically, a long int value. This function confuses some users because it doesn’t return a value; it merely sets a value into the time_t variable.

  • ctime(): The ctime() function takes the time_t variable containing the current time (courtesy of the time() function) and converts it into a displayable date-time string.

  • localtime(): This function fills a tm structure variable with information based on the time value stored in a time_t variable. The function returns the address of the tm structure, so it gets all messy with structures and pointers and that -> operator.

  • difftime(): The difftime() function compares the values between two time_t values and returns a float value as the difference in seconds.

  • sleep(): The sleep() function suspends program execution for a given number of seconds.

C features many more time functions, and what it doesn’t offer, you can program on your own. The whole point of the exercise, of course, is to figure out what time it is, or at least what time the program believes it to be.