ZedZerg ZedZerg - 9 days ago 4
C Question

C - time_t string representation

I am new to C programming and I would like some help with a simple task.

So I have this function:

char *time2str(time_t time) {
static_char *str_fmt = "%02d/%02d/%4d %02d:%02d";
char *time_s = "";

return time_s;
}


What I would like to do is get in DD/MM/YYYY HH:MM format the time and store it in time_s variable so that I can return it. My problem is that I cannot figure out how to format the string and store it WITHOUT printing it. All I have found so far is the sprint method that actually prints the formatted string when storing it too, which is not what I want.

In a few words, I would just like the time from time_t time in the format I mentioned stored in time_s.

Sorry if I didn't explain everything properly but I'm new in C programming.

Answer

You need sprintf which is similar to printf but "prints" the result into a buffer rather than on the screen.

Returning the pointer to a static buffer:

char *time2str(time_t time) {
     static_char *str_fmt = "%02d/%02d/%4d %02d:%02d";

     static char time_s[20];                             // ugly, 20 is hopefully enough
  // ^ static is important here, because we return a pointer to time_s
  //   and without static, the time_s buffer will no longer exist once the
  //   time2str function is finished

     sprintf(time_s, str_fmt, time.....);
     return time_s;
}

or (better), we provide a buffer (long enough) where the converted string is to be placed:

void time2str(time_t time, char *time_s) {
     static_char *str_fmt = "%02d/%02d/%4d %02d:%02d";
     sprintf(time_s, str_fmt, time.....);
     return time_s;
}
...
char mytime[20];                                         // ugly, 20 is hopefully enough
time2str(time, mytime);
printf("mytime: %s\n, mytime);

or the time2str function returns a newly allocated buffer that will contain the converted string. That buffer must be freed later with free.

char *time2str(time_t time) {
     static_char *str_fmt = "%02d/%02d/%4d %02d:%02d";
     char *time_s = malloc(20);                          // ugly, 20 is hopefully enough
     sprintf(time_s, str_fmt, time.....);
     return time_s;
}
...
char *mytime = time2str(time);
printf("mytime: %s\n, mytime);
free(mytime);

Completing the arguments of sprintf is left as an exercise to the reader.

Disclaimer: non tested, non error checking code meant only for demonstration purposes.

Comments