Time and Date Manipulation
By Danny Kalev, C++ Pro

The Notion of Time
All the time and date functions and data structures are declared in the standard header <ctime> (<time.h> in C and pre-standard C++). Time is represented as a positive integer of type time_t that contains the number of seconds elapsed since the epoch, or January 1st, 1970, 00:00 GMT. time_t is a platform-defined signed integral type containing at least 32 bits. As large as this type may seem, on 32-bit architectures time_t will roll over on January 18, 2038. Fortunately, hardware architectures are gradually switching to a 64-bit time_t, which can represent billions of years.

Retrieving the Current Time
The function time() retrieves the current calendar time from the system's clock:


time_t time(time_t * tp);

In systems in which no clock is available, the function returns -1. If tp is not null, the value is also written to *tp. The following program retrieves the current time and displays it in its raw format:


#include <ctime>
using namespace std;
int main()
{
 time_t curr=time(0);
 cout << "current time is: " << curr <<endl;
}

The output is a number such as 980898685. This is the number of seconds that have elapsed since the epoch (for more fine-grained time measurement functions, check the following 10-Minute Solution). As you can see, time_t isn't a human-readable format. To present the current time and date in a human-readable format you have to convert a time_t value into a string using the ctime() function:


char * ctime(const time_t * tp);

This function returns a null-terminated string of the form:
Wed Jan 31 01:51:25 20001\n\0

Note: All the <ctime> functions, data structures and typedef names are declared in namespace std, as does every Standard Library component. Therefore, you need to a using-directive, a user-declaration of qualified names, e.g., std::time_t, std::localtime() etc., to refer to them. However, Visual C++ is not compliant in this regard and still declares all <ctime> components in the global namespace. Therefore, you should remove the using-directive from the source listings if you intend to compile them with Visual C++.




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.

  
Next: Breaking It into Pieces


Introduction
Breaking It into Pieces
Time Differences and Time Zones
 


Find Out More
Implementing a Stopwatch Class for Performance Measurements

Time and Date.com

C++ Boost Timer Library



 


Sponsored Links