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:
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:
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 );
- The standard library also provides a function called localtime which converts a time_t object to the local time, instead of to UTC time.
- There are several functions available to further convert a tm structure into a human-readable string, ready for output to the user.
- 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.
- 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,
Matt Billock is a software engineer who has been writing since 1999. He has been published in TechTrax, an online computer support magazine. Billock holds a Bachelor of Science in computer science from Iowa State University and a Master of Science in computer graphics and animation from DePaul University.