Home > Software design >  Convert time to formatted string; result is truncated
Convert time to formatted string; result is truncated

Time:10-08

I need to convert a time_t variable into string of format DD/MM/YYYY/HH:mm. I made the following function.

int time_to_str(time_t value, char *string)
{
    struct tm *timeinfo;
    time(&value);
    timeinfo = localtime(&value);

    strftime(string, sizeof(string), "%d/%m/%Y/%H:%M", timeinfo);
}

Testing the function with the following:

time_t variable = time(NULL);
char buffer[100];

time_to_str(variable, buffer);

printf("%s", buffer);

I get the following output and I don't see the problem... Any ideas?

07/10/

CodePudding user response:

The second argument of strftime should be the size of the buffer to write to, i.e. 100 in this case. sizeof(string) results in the size of a pointer to char, which is usually 4 or 8. Hence, strftime only writes several characters to the string buffer.

For more information, see the documentation for strftime.

  • Related