Home Segments Index Top Previous Next

589: Mainline

A more advanced way to display time information is to appeal to other time-library mechanisms that enable you to transform a time-structure pointer into displayed forms under the direction of strings similar to those you find in printf statements. Here is an example in which time specifications dictate that the hour, minute, and PM are to be displayed:

/* Declare variable to hold elapsed seconds since 1970 */ 
time_t elapsed_seconds; 
/* Declare pointer to an object containing time information */ 
struct tm *time_structure_pointer; 
/* Declare buffer to hold time string */ 
char *time_buffer[100]; 
... 
/* Fetch elapsed seconds from operating system */ 
time(&elapsed_seconds); 
/* Use elapsed seconds to update time structure object */ 
time_structure_pointer = localtime (&elapsed_seconds); 
/* Use time-structure object to fill time buffer */ 
strftime (time_buffer, 100, "%I:%M %p", time_structure_pointer); 
/* Use time buffer to display the time */ 
printf ("The time is %s.\n", time_buffer); 

Executing all these statements displays a line such as the following:

The time is 12:17 PM. 

The key statement, obscurely, is the one with strftime, which is an acronym for string format time:

           *-- Name of time buffer 
           |            
           |           *-- Length of time buffer 
           |           | 
           |           |    *-- String with print specifications 
           |           |    |            
           |           |    |           *-- Name of time pointer 
           |           |    |           | 
           v           v    v           v 
strftime (time_buffer, 100, "%I:%M %p", time_structure_pointer); 
                              ^  ^  ^ 
                              |  |  | 
                              *--*--*-- Special print specifications 
                                        specific to calls to strftime