Sunday, February 15, 2009

C++ Snippets: Time

There's been a lot of talk about Unix time lately surrounding 1234567890 day. If you read some of the recent articles you might be left with the impression that some of us actually tell time this way. Only hard-core Unix sysadmins actually do that. The rest of us can use standard C++ library functions to get the current system time and convert it to a human-readable format.

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
tm* timeinfo;

time_t seconds = time(NULL);
timeinfo = localtime(&seconds);

cout << "Seconds since the epoch: " << seconds << endl;
cout << "Local time: " << asctime(timeinfo) << endl;
return 0;
}

Here I'm using three functions and one stuct from the C++ standard ctime library to get the time and display it. The time function gets the number of seconds since January 1, 1970 (the start of the Unix epoch) from the operating system. The localtime function converts the time in seconds to a tm structure representing the calendar date and time. Finally, the asctime function converts the tm stucture to a human-readable string format.

Compile the program above using g++, then run it to see the following output.
$ ./a.out
Seconds since the epoch: 1234712674
Local time: Sun Feb 15 10:44:34 2009
Naturally, you'll see different results depending on when you run the executable.

No comments: