Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 226
o01 Avatar asked Oct 07 '09 11:10

o01


3 Answers

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.

like image 126
John Carter Avatar answered Oct 16 '22 21:10

John Carter


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

like image 37
sepp2k Avatar answered Oct 16 '22 20:10

sepp2k


#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.

like image 4
pmg Avatar answered Oct 16 '22 21:10

pmg