views:

1008

answers:

3

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?

+3  A: 

Take a look at the strftime function, which allows you to write the time into a char array with a format of your choice.

sepp2k
+1  A: 
#include <stdio.h>
#include <time.h>

/* get seconds since the Epoch */
time_t secs = time(0);

/* convert to localtime */
struct tm *local = localtime(&secs);

/* and set the string */
sprintf(timeString, "%02d:%02d:%02d", local->tm_hour, local->tm_min, local->tm_sec);

The important types for dealing with time (the wall-clock type of time, not process/thread time) are time_t and struct tm.
With some work you can convert between one and the other, but you have to pay attention to local time versus UTC time.

Peruse the description of <time.h>, try the functions there until you grok time in C.

Again, pay attention to UTC time and local time.

pmg
+4  A: 

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.

therefromhere
Ah, of course. Thanks dude!
Orolin
I usually take the pessimistic approach and over-allocate buffer sizes. For example, I'd declare `timeString[]` to be 20 or so chars. Memory is cheap, and we're only talking a few extra bytes here. And it saves you when you later decide to change the format string but forget to update the buffer length.
Loadmaster