How to Convert Epoch Time in C++by Matt Billock
The time function in the C++ standard library returns seconds elapsed since a specific, standardized date and time known as the epoch. While this value contains all of the information needed to calculate the current time and date of the system, writing your own epoch time translation code is error prone. Using the standard library's provided time conversion functions makes this translation process trivial, allowing you to focus on the more complex portions of your application.
Include the C++ standard library's time functionality into your application. Add the following line to the top of your include list: #include
Obtain the seconds elapsed since the epoch, and store it locally. Do this by calling time(), and storing the result into an object of type time_t. The time function also accepts a pointer to an object of type time_t as an argument, but it is simpler to store this object locally on the stack: time_t timeSinceEpoch = time(NULL);
Create a time structure to store the result of the time conversion. This structure is defined in the time.h header file as a structure named tm, and provides conveniently-named member variables for each component of the converted time: tm timeResult;
Use one of the built-in conversion functions to store the time_t value obtained earlier as a tm structure. For simplicity, the following code converts a time_t object into a UTC tm structure: timeResult = gmtime( &timeSinceEpoch; );
- check The standard library also provides a function called localtime which converts a time_t object to the local time, instead of to UTC time.
- check There are several functions available to further convert a tm structure into a human-readable string, ready for output to the user.
- close Be aware of the epoch that your computer is counting from, as this may affect the output value. Most computers count from January 1, 1970.
- close The maximum precision of the above code is one second. To obtain more precise times with values of less than one second, you will need to use a different method,
Items you will need
- photo_camera Martin Poole/Digital Vision/Getty Images