Best way to format a tm struct?

Hi all

I've got a time/date in the form of a tm struct and was wondering what's the best way to format it into a string of the format "MM/DD/YYYY HH:MM:SS". If I try to do sprintf or string.Format that doesn't work with single digit numbers.

I know I could just do a bunch of if statements but does anyone know of a better way?
The C library has the asctime() functions:

char * asctime ( const struct tm * timeptr );

http://www.cplusplus.com/reference/clibrary/ctime/asctime/
That's a good function but I need it to be more customizable. I found this function in the same library:

http://www.cplusplus.com/reference/clibrary/ctime/strftime/

but for some reason it behaves weirdly with my program. Here's my code:

1
2
3
4
5
6
7
struct tm stCreateT = {0};
tm *cCreateT = &stCreateT;
tm * cCreateTime = cFileCreationTime.GetGmtTm(cCreateT);
char chDate[10] = "";
char chTime[8] = "";
strftime(chDate, 10, "%m/%d/%Y", cCreateTime);
strftime(chTime, 8, "%H/%M/%S", cCreateTime);


After this is done, chDate is, for example, " 7/29/ ", not setting the month to "07" like the function is supposed to do and ignoring the year completely, even though debugging shows that all the data is in the tm pointer correctly.
Not sure about the leading zeros. are you using VC or something else, like gcc?

But your buffer is too small: remember the null terminator!

"07/29/2011" is actually '0','7','/','2','9','/','2','0','1','1','\0' which is 11 chars.

Similarly you need 8 chars for the time.
%02d

for example, says to format an int (d) into a field width of exactly 2 characters, padding with 0 to the left as necessary.
Topic archived. No new replies allowed.