This paper introduces the processing of time and date in C language in detail.
Chuck Allison is a software architect at the Family History Research division of the Church of Christ, Salt Lake City St. Latter Day Church headquarters. He has a Bachelor of Mathematics and a master's degree in mathematics. He has been programming since 1975, and since 1984 he has been engaged in the teaching and development of C language. His current interest is in object-oriented technology and its education. He is a member of the X3j16,ansi C + + standardization committee. Send e-mail to allison@decus.org or call (801) 240-4510 to get in touch with him.
Most operating systems have the means to get the current date and time. By defining the library functions in Time.h, ANSI C can get this information in many different forms. function time returns a value of type time_t (usually long) that encodes the current date and time during the run. You can then pass this return value to other functions that can decode and format the value.
The program in Listing 1 uses functions time,localtime and strftime to output the current date and time in different forms. The function localtime decodes the encoded time into the following struct:struct tm
{
int tm_sec; /* (0 - 61) */
int tm_min; /* (0 - 59) */
int tm_hour; /* (0 - 23) */
int tm_mday; /* (1 - 31) */
int tm_mon; /* (0 - 11) */
int tm_year; /* past 1900 */
int tm_wday; /* (0 - 6) */
int tm_yday; /* (0 - 365) */
int tm_isdst; /* daylight savings flag */
};
Every time you call localtime, it rewrites a static structure and returns the address of the struct (so that you can only get one of these structures in a program at a time and not make a significant copy). function CTime Returns a pointer to a static string that contains the full time and date in a standard format. Strftime formats a string based on the user's specified format (for example,%a represents the name of each day of the week). Table 1 lists the full list of format descriptors.