Time into string with HH:MM:SS format (C-programming)

o01 picture o01 · Oct 7, 2009 · Viewed 40.9k times · Source

I need to get the current time in a "HH:MM:SS"-format into a character array (string) so I can output the result later simply with a printf("%s", timeString);

I'm pretty confused on the timeval and time_t types btw, so any explanation would be awesome:)

EDIT: So I tried with strftime etc, and it kinda worked. Here is my code:

time_t current_time;
struct tm * time_info;
char timeString[8];

time(&current_time);
time_info = localtime(&current_time);

strftime(timeString, 8, "%H:%M:%S", time_info);
puts(timeString);

But the output is this: "13:49:53a??J`aS?"

What is going on with the "a??J`aS?" at the end?

Answer

John Carter picture John Carter · Oct 7, 2009

You're getting garbage from this code:

time_t current_time;
struct tm * time_info;
char timeString[8];

time(&current_time);
time_info = localtime(&current_time);

strftime(timeString, 8, "%H:%M:%S", time_info);
puts(timeString);

Because you're not allowing space for a null terminator (\0) on the string, so when the string it printed, it doesn't know where the end is and inteprets random garbage in the next bit of memory as part of the string.

Change it to this:

time_t current_time;
struct tm * time_info;
char timeString[9];  // space for "HH:MM:SS\0"

time(&current_time);
time_info = localtime(&current_time);

strftime(timeString, sizeof(timeString), "%H:%M:%S", time_info);
puts(timeString);

And it'll work correctly because strftime() will have enough space to add a \0. Note that I'm using sizeof(array) to avoid the risk forgetting to change the number in both places.