Time per line with HH: MM: SS format (C-programming)

I need to get the current time in the format "HH: MM: SS" in an array of characters (string) so that I can output the result later simply with printf("%s", timeString);

I'm pretty confused about types timevaland time_tbtw, so any explanation would be awesome :)

EDIT: So I tried using strftime, etc., and it 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 conclusion is: "13: 49: 53a ?? J`aS?"

What happens to โ€œ a ?? J`aS? โ€ At the end?

+5
source share
3 answers

You get 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);

(\ 0) , , , , , , .

:

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);

, strftime() \0. , sizeof (array), .

+8

strftime, char .

+4
#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);

( , /) time_t struct tm.
- , UTC.

<time.h>, , C.

UTC .

+2
source

All Articles