It is common for programmers to need to get the time for some reason or another. You might simply wish to display the current time to the user, timestamp a file, or check to see if the current time is within some range of dates. C++ provides you with a rich set of tools to do this. You simply need to include the ctime header file and you can access these functions and objects (see Table 4.3).
Function | Purpose |
---|---|
time_t time ( time_t * timer ); | Gets the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC from the system clock. |
struct tm * localtime (const time_t * timer ); | Converts timer to tm structure, adjusting to the local time zone. |
double difftime (time_t timer2, time_t timer1 ); | Calculates the time difference between timer1 and timer2 in seconds. |
struct tm * gmtime (const time_t * timer ); | Converts timer to tm structure, adjusting to GMT time zone. |
char * ctime (const time_t * timer ); | Converts time to a string containing time and date adjusted to local time zone in readable format. This is usually used to present the time in a more readable format. |
This is not an exhaustive list, but it does show you the most important functions found in the ctime header file. This might be even clearer for you if you saw an example of this in action. With that in mind, please consider the following example.
Step 1: Enter the following code into your favorite text editor.
#include <iostream> #include <ctime> using namespace std; int main () { time_t rawtime; time ( &rawtime ); cout << "Current date and time is: "<< ctime (&rawtime); return 0; }
Step 2: Compile the code and run it. You should see something like what is depicted in Figure 4.10.
Figure 4.10: Using time functions.
Hint! | The C method was to include <time.h> and you may still see this occasionally. Most of the functions are the same, at least calling them is the same. |