这段时间一直在处理服务器产生的日志,需要经常获取时间和格式化输出,所以对C/C++的时间操作总结和归纳一下。在网上找了很多的blog,大多是写函数的具体用法,时间存储结构的含义,并不是不这种介绍方式不好,只是我很难快速从中提取出主要的内容。
时间函数及时间结构之间的关系图
时间的存储结构一般有四种,time_t、struct tm、struct timeval、struct timespec。下图给出了时间存储结构的精度,及其与时间函数的关系图,
时间结构及其获取函数
time_t
time_t 类型表示从1970-01-01 00:00:00时开始到现在秒数,精确度:秒(second)。
time_t 类型定义在头文件 /usr/include/sys/time.h 中:
#define _TIME_T
typedef long time_t;
#endif
time_t 类型变量获取函数:time_t time(time_t* lpt):
#include<time.h>
time_t ts;
ts = time(0); // 方法一
ts = time(NULL); // 方法二
ts = time((size_t)NULL); // 方法三
time(&ts); // 方法四
struct tm
struct tm 结构精度为:秒(second),结构定义如下:
struct tm
{
int tm_sec; /* 代表目前秒数,正常范围为0-59,但允许至61秒 */
int tm_min; /* 代表目前分钟数,范围0-59 */
int tm_hour; /* 从午夜算起的时数,范围为0-23 */
int tm_mday; /* 目前月份的日数,范围01-31 */
in