Time Differences and Time Zones
To compute the time difference between two dates, use the standard function difftime():
double difftime (time_t t1, time_t t2);
This function takes two variables of type time_t, and returns t2-t1 expressed in seconds. For example:
time_t now=time(0);
time_t last_week=now-(60*60*24*7); // a week ago
double seconds=difftime(now, last_week);
To calculate time zone differences, use the gmtime() function:
struct tm * gmtime(const time_t * tp);
gmtime() converts the calendar time into GMT equivalent. The following code calculates the difference between your local time zone and GMT:
time_t curr=time(0);// current local time
tm local=*gmtime(&curr);// convert curr to GMT, store as tm
time_t utc=(mktime(&local));// convert GMT tm to GMT time_t
double diff=difftime(utc,curr)/3600; //difference in hours
| Note:
The term Greenwich Mean Time (GMT) was changed to Universal Time Coordinated (UTC) several years ago but GMT is still widely used in the literature and more importantly, it's used in the Standard Library's function names. |
The <ctime> library provides the building bricks of time retrieval, processing and formatting. Using this library instead of any other proprietary library offers three major benefits: portability, efficiency and minimal memory and speed overhead. For more advanced uses, you can find useful open source utilities that implement timers and progress bars that are based on the <ctime> library.
Danny Kalev is a system analyst and software engineer with 12 years of experience, specializing in C++ and object-oriented analysis and design. He is a member of the ANSI C++ standardization committee and the author of ANSI/ISO C++ Professional Programmer's Handbook (Que, 1999, ISBN: 0789720221); check out the review. He can be reached at dannykk@inter.net.il.