Breaking It into Pieces
To break the time into its constituents, e.g., year, month, and day of the week, we use the tm struct:


struct tm
{
  int tm_sec; /*seconds after the minute (0-61)*/
  int tm_min; /*minutes after the hour (0-59)*/
  int tm_hour; /*hours since midnight (0-23)*/
  int tm_mday; /*day of the month (1-31)*/
  int tm_mon; /* months since January  (0-11)*/
  int tm_year; /* elapsed years since 1900 */
  int tm_wday; /* days since Sunday (0-6)*/
  int tm_yday; /*days since January 1st  (0-365)*/
  int tm_isdst; /*1 if daylight savings is on, zero if not,
                -1 if unknown*/
};

Remember: the key to manipulating date and time is knowing how to convert time_t to tm and vice versa. To fill a tm object with the local time, use the function localtime():


struct tm* localtime (const time_t *pt);

localtime() takes a pointer to a valid time_t object, converts it to a local static tm struct and returns its address. Note that subsequent invocations of localtime() override the previous value of its local static tm object. Therefore, you should copy the result immediately to your own tm object. The following program fills a tm object with the current local time:


#include <ctime>
using namespace std;
int main()
{
 time_t curr;
 tm local;
 time(&curr); // get current time_t value
 local=*(localtime(&curr)); // dereference and assign
}

To convert a tm struct to time_t, use the mktime() function:


time_t curr;
tm local;
time(&curr); // get current time_t value
local=*(localtime(&curr)); // dereference and assign
time_t temp=mktime(&local); // temp and curr are equal
 




Back to the Beginning
 
Next: Time Differences and Time Zones


Introduction
Breaking It into Pieces
Time Differences and Time Zones
 


Each operating system and framework offers proprietary APIs to access the system's date and time. However, the overhead of using these libraries and the lack of portability make them unsuitable for cross-platform and compact applications.




Use the standard date and time library to retrieve and process time in a portable and efficient manner.


Find Out More
Implementing a Stopwatch Class for Performance Measurements

Time and Date.com

C++ Boost Timer Library



 


Sponsored Links