How to Convert Seconds Since Epoch to Time in C++

How to Convert Seconds Since Epoch to Time in C++ thumbnail
Time can be a complex issue.

The “Time” function in UNIX, C and C++ returns the number of seconds since midnight the first of Janurary 1970, Greenwich Mean Time. This is known as epoch time. When programmers suggested that this was not always convenient, designers overloaded the time function so it could be used in two ways: to give epoch time and to give the time as a character string that represented the years, days, hours, minutes and seconds since the first of January 1970 GMT. Since then, a library of functions has been created that contains functions that convert this string into something more useful.

Things You'll Need

  • The time.h library
Show More

Instructions

    • 1

      Include the time.h library in your program with the “#include <time.h>;” instruction. Define a couple of variables of type time_t with the instruction “time_t time1, time2;” to hold the two versions of the time string that will be developed during the conversion. Call the time function like this: “time (&time1);” to put the string you want in the variable time1.

    • 2

      Covert the information in the time1 string into local time with the “localtime” function that takes the address of time1 as an input parameter and puts the results in the variable time2. The statement looks like this: “time2 = localtime(&time1);” — time2 now contains the local time, but it is not quite in the format to print.

    • 3

      Transform the time into its final, printable form with the asctime function. This transformation can be done right in the print statement. The print statement looks like this: “printf (“The current time is %s”, asctime(time2));” which will print something like this: “The current time is Fri Sep 23 22:01:47 2011.”

Tips & Warnings

  • The intended use for the “time” function is to measure elapsed time. When used in this original form the input parameter is NULL and a value is returned. The variable that the return value is assigned to must be time_t type. So the code to measure how long it takes to run procedure XYZ would look like this: “#include <time.h>; time_t t1,t2; t1 = time(NULL); XYZ; t2 = time(NULL); printf “The time it takes to run procedure XYZ is %d seconds”, t2 – t1);” which will print something like “The time it takes to run procedure XYZ is 147 seconds.”

  • The type time_t and the functions time(), localtime() and asctime() are all defined in the time.h library. If you do not include the time.h library, all of these will be flagged as undefined.

Related Searches:

References

Resources

  • Photo Credit Thinkstock/Comstock/Getty Images

Comments

Related Ads

Featured