linux获取时间戳(linux 获取 时间戳)-编程之家

linux 获取时间戳的函数有哪些?

1.获取当前时间

a. 获取系统当前的秒数和毫秒数

struct timeval tv;

gettimeofday(&tv, NULL);

b. 获取系统当前时间的秒数

time_t now = time(NULL)

2. 获取日历时间

a. gmtime函数返回一个struct tm

time_t now = time(NULL);

struct tm t1 = *gmtime(&now);  // 获取UTC时间  

struct tm t2 = *localtime(&now);  // 获取local时间

time_t seconds  = static_cast<time_t>(tv.tv_sec);

b. gmtime_r函数直接赋值给传入的第二个参数

struct tm tm_time;

gettime_r(&seconds, &tm_time);

localtime_r(&seconds, &tm_time);