Thursday, March 12, 2009

C++ Snippets: Time Part 2

In my previous post about telling time in C++, I showed how to display the current Linux system time in a human-readable format. Today I want to go a little bit beyond that and explain how to customize that format.

If you read my previous post, you saw that the asctime function always returns the time in the same format (Thu Mar 12 18:30:50 2009). That's much better than displaying the time in the number of seconds since January 1, 1970, but it still leaves room for improvement.

I'm going to show you how to create a custom format to display the date and time however you choose using the strftime function from the ctime library. I want to rearrange things so the time above would be displayed as:

Thursday, March 12, 2009 06:30:50 PM

First, let's take a look at the arguments that strftime takes.

char *str - A buffer that will hold the formatted output. Strftime was originally a C function, so we can't just return a string. That's okay, though, we'll just make the buffer big enough to hold any time and date in our specified format.

size_t maxsize – The maximum number of characters that will be copied to the output buffer. This should be the same value as the size of the buffer used as the first input parameter.

const char *fmt
– Specifies exactly how we want the time to be formatted. There are some special format codes that I'll go over next, but be aware that normal text can be included as well.

struct tm *time
- The time value we want to format.

In order to display the time in the desired format, we'll use the following format specifiers:
%A - full weekday name
%B - full month name
%d - day of the month
%Y - year in (with the century)
%I - hour in 12 hour format
%M - minute as a number
%S - second as a number
%p - locale equivalent of AM/PM
We'll combine all of these format codes together, along with normal text delimiters (commas, colons, and spaces) to form one long format string.
%A, %B %d, %Y %I:%M:%S %p
Finally, here's the code:
#include <iostream>
#include <ctime>

using namespace std;

int main ()
struct tm * timeinfo;
char buffer [80];
time_t seconds = time(NULL);

timeinfo = localtime( &seconds );
char format[] = "%A, %B %d, %Y %I:%M:%S %p";

strftime(buffer, 80, format, timeinfo);
cout << "Local time: " << buffer << endl;

return 0;
After compiling the code snippet above, you should see output similar to the following:
$ ./a.out
Local time: Thursday, March 12, 2009 06:53:13 PM

No comments: