|
|
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.