Linux系统中时间的获取和使用

2019-01-16 20:50:38于海丽

Time1: 1533289490s
Time2: 1533289490s, 133547us
Time3: 1533289490s, 133550060ns

可视化时间

tm结构体

得到的时间戳不能直观的展示现在的时间,为此需要使用tm结构体来表示成我们日常所见的时间,该结构体定义如下:

struct tm { int tm_sec; /*秒,正常范围0-59, 但允许至61*/ int tm_min; /*分钟,0-59*/ int tm_hour; /*小时, 0-23*/ int tm_mday; /*日,即一个月中的第几天,1-31*/ int tm_mon; /*月, 从一月算起,0-11*/ 1+p->tm_mon; int tm_year; /*年, 从1900至今已经多少年*/ 1900+ p->tm_year; int tm_wday; /*星期,一周中的第几天, 从星期日算起,0-6*/ int tm_yday; /*从今年1月1日到目前的天数,范围0-365*/ int tm_isdst; /*日光节约时间的旗标*/ };

time_t转成tm

gmtime 和localtime可以将time_t类型的时间戳转为tm结构体,用法如下:

struct tm* gmtime(const time_t *timep); //将time_t表示的时间转换为没有经过时区转换的UTC时间,是一个struct tm结构指针 stuct tm* localtime(const time_t *timep); //和gmtime功能类似,但是它是经过时区转换的时间,也就是可以转化为北京时间。

固定格式打印时间

得到tm结构体后,可以将其转为字符串格式的日常使用的时间,或者直接从time_t进行转换,分别可以使用以下两个函数达到目的。不过这两个函数只能打印固定格式的时间。

//这两个函数已经被标记为弃用,尽量使用后面将要介绍的函数 char *asctime(const struct tm* timeptr); char *ctime(const time_t *timep);

调用示例:

#include <time.h> #include <sys/time.h> #include <iostream> #include <stdlib.h> using namespace std; int main() { time_t dwCurTime1; dwCurTime1 = time(NULL); struct tm* pTime; pTime = localtime(&dwCurTime1); char* strTime1; char* strTime2; strTime1 = asctime(pTime); strTime2 = ctime(&dwCurTime1); cout << strTime1 << endl; cout << strTime2 << endl; return 0; }

结果:

Fri Aug 3 18:24:29 2018
Fri Aug 3 18:24:29 2018

灵活安全的时间转换函数strftime()

上述两个函数因为可能出现缓冲区溢出的问题而被标记为弃用,因此更加安全的方法是采用strftime方法。

/* ** @buf:存储输出的时间 ** @maxsize:缓存区的最大字节长度 ** @format:指定输出时间的格式 ** @tmptr:指向结构体tm的指针 */ size_t strftime(char* buf, size_t maxsize, const char *format, const struct tm *tmptr);

我们可以根据format指向字符串中格式,将timeptr中存储的时间信息按照format指定的形式输出到buf中,最多向缓冲区buf中存放maxsize个字符。该函数返回向buf指向的字符串中放置的字符数。