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(¤t_time);
time_info = localtime(¤t_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?
You're getting garbage from this code:
time_t current_time;
struct tm * time_info;
char timeString[8];
time(¤t_time);
time_info = localtime(¤t_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(¤t_time);
time_info = localtime(¤t_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.
Take a look at the strftime function, which allows you to write the time into a char array with a format of your choice.
#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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With