#include <sys/time.h>
1、int gettimeofday(struct timeval*tv, struct timezone *tz);
其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:
struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST 时间的修正方式*/
}
timezone 参数若不使用则传入NULL即可。
而结构体timeval的定义为:
struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
它获得的时间精确到微秒(1e-6 s)量级。
2、struct tm *localtime(const time_t *clock)和struct tm* localtime_r( const time_t* timer, struct tm* result )
多线程应用里面,应该用localtime_r函数替代localtime函数,因为localtime_r是线程安全的。
使用如下:
struct timeval tv;
gettimeofday(&tv, NULL);//获取1970-1-1到现在的时间结果保存到tv中
uint64_t sec = tv.tv_sec;
struct tm cur_tm;//保存转换后的时间结果
localtime_r((time_t*)&sec, &cur_tm);
char cur_time[24];
snprintf(cur_time, 24, "%d-%02d-%02d %02d:%02d:%02d", cur_tm.tm_year+1900,
cur_tm.tm_mon+1, cur_tm.tm_mday, cur_tm.tm_hour, cur_tm.tm_min, cur_