Could you please help me how to format a struct timeval
instance to human readable format like "2010-01-01 15:35:10.0001"?
views:
354answers:
3
+2
A:
Convert the tv_sec
using localtime
, and strftime
, then append tv_usec
part.
Didier Trosset
2010-03-09 12:39:09
A:
You can use the strftime function to convert a date and time to a string.
Frerich Raabe
2010-03-09 12:40:27
+4
A:
You need to manually append the microseconds part, since it's not in the struct tm
that strftime() deals with. Here's a snippet:
struct timeval tv;
time_t nowtime;
struct tm *nowtm;
char tmbuf[64], buf[64];
gettimeofday(&tv, NULL);
nowtime = tv.tv_sec;
nowtm = localtime(&nowtime);
strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm);
snprintf(buf, sizeof buf, "%s.%06d", tmbuf, tv.tv_usec);
Note how we use explicit precision of 06
to get a zero-filled microseconds field. Since the microseconds go from 0 to 999,999, it must always be padded to 6 digits. We don't want to misrepresent e.g. 57 microseconds as 570,000 (compare "1.57" vs "1.000057").
unwind
2010-03-09 12:45:50