//version 1: no time zone
std::string getTimeStamp()
{
char fmt[64] = "";
char timestampBuf[128] = "";
struct timeval tv;
struct tm tm;
gettimeofday(&tv, NULL);
localtime_r(&tv.tv_sec, &tm); // thread safe
strftime(fmt, sizeof(fmt), "%Y-%m-%d %H:%M:%S.%%06u", &tm); //no time zone
sprintf(timestampBuf, fmt, tv.tv_usec);
return timestampBuf;
}
//version 2: with time zone
string getTimeStamp()
{
struct timeval t1b;
struct timezone tz;
struct tm tm;
char timeStamp[256] = {0}; // intialize char array
gettimeofday(&t1b,&tz);
localtime_r(&t1b.tv_sec, &tm); // thread safe
strftime(timeStamp,sizeof(timeStamp),"%Y%m%d_%H%M%S",&tm);
return timeStamp;
}
头文件 <sys/time.h>