How to Convert Epoch Time in C++

By Matt Billock

The C++ standard library allows you to convert from epoch time to a specific time zone quickly and easily.
i Martin Poole/Digital Vision/Getty Images

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 );

×