views:

506

answers:

2

Hello, is there any way to convert a time_t to a string with the format YYYY-MM-DD HH:MM:SS automatically, keeping the code portable?

A: 

Your only real option off the top of my head is either to write your own routine, or use the ctime() function defined in POSIX.1/C90. ctime() is certainly worth looking into, but if your date is not in the right timezone already, you will run into issues.

EDIT: I didn't think about using localtime as mentioned by Jerry below. Converting it to a struct tm does give you more possibilities including what he mentions, and strptime().

jer
strptime should be strftime, right?
jim mcnamara
Nope, strftime was mentioned, but strptime was not, they are two separate (yet similar) functions. However, while strftime is part of C90, strptime is not, so if it doesn't exist on the platforms you target, ignore that part.
jer
+5  A: 

Use localtime to convert the time_t to a struct tm. You can use strftime to print the desired data from that.

char buff[20];
time_t now = time(NULL);
strftime(buff, 20, "%Y-%m-%d %H:%M:%S", localtime(&now));
Jerry Coffin
+1 good answer. But use localtime_r() in case your code is ever used in a re-entrant environment.
Amardeep
@Amardeep: He specifically asked for portability, and `localtime_r` may not qualify in that regard (depends on what targets he cares about).
Jerry Coffin