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