DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
No more ctime(3C) errors - Time(3C++)

No more ctime(3C) errors - Time(3C++)

C programmers must often make time calculations in their programs. When they do so, however, the resulting code is likely to be difficult to write, debug, and maintain. The reason is that the time facilities provided by the standard C libraries and UNIX® system calls are seldom at the appropriate level of abstraction required by the programmer to express notions of time in a clear and comprehensible manner.

For example, suppose we need to print the month, day, year, and time-of-day exactly thirty days from now. Here is a C-like solution using the facilities described in ctime(3C) and time(2):

       #include <sys/types.h>    see time(2)
       #include <time.h>         see ctime(3C)
       main(){
           time_t now = time(0);
           time_t hence = now + 30*24*60*60;
           struct tm* p1 = localtime(&hence);
           char* p2 = asctime(p1);
           printf("%s\ n",p2);
       }

First note that when using the standard facilities, all calculations are carried out in units of seconds. Thus, the current time is represented as the number of seconds elapsed since January 1, 1970 at 0h GMT, and thirty days is represented by the 2,592,000, which we have made slightly more transparent by writing it as a product. localtime() computes the ``broken-down'' components of time (day, month, year, hour, minutes, seconds, etc.) stores them in the static tm structure, and returns a pointer to the structure. Since the structure is overwritten by subsequent ctime(3C) calls, the pointer must be used quickly. asctime() takes the tm components and formats them in a static buffer using a fixed format. It returns a pointer to this buffer, which also must be used quickly to avoid information loss. Finally, note that if we were required to display the result in a timezone other than the one in which our host machine is located, the code would be considerably messier and more error-prone.

Furthermore, the standard UNIX representation of Time doesn't work after year 2038, which is an unreasonable limit for some applications.


Next topic: Introduction to Time(3C++)

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004