1、结构
time_t:为长整型的别名(typedef long time_t);从一个时间点(一般是1970年1月1日0时0分0秒)到那时的秒数.
#ifndef __TIME_T
#define __TIME_T /* 避免重复定义 time_t */
typedef long time_t; /* 时间值time_t 为长整型的别名*/
#endif
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; /*日光节约时间的旗标*/
};
timeval结构体:该结构体以1970-01-01 00:00:00 +0000 (UTC),也就是Unix中的Epoch作为0,之后的时间都是相对于Epoch流逝的秒和毫秒数。直接用函数 gettimeofday 就可以获得时间。
struct timeval
{
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
2、获取时间函数
time():
函数定义:time_t time(time_t *seconds)
函数说明:C 库函数 time_t time(time_t *seconds) 返回自纪元 Epoch(1970-01-01 00:00:00 UTC)起经过的时间,以秒为单位。如果 seconds 不为空,则返回值也存储在变量 seconds 中。
返回值:以 time_t 对象返回当前日历时间。
gettimeofday():
头文件:#include<sys/time.h>
函数定义:int gettimeofday(struct timeval *tv,struct timezone *tz)
函数说明:
用于获取调用该代码时,距离Epoch的时间
3、时间转换函数:
gmtime():
函数定义:struct tm *gmtime(const time_t *timep);
函数说明:接收一个time_t*的指针,然后将其转换为了代表gmt时间的结构体指针,需要年月日时分秒等,都可以从这个返回的tm结构体中获取。由于使用的是GMT时间,因此,比北京时间慢了8小时,如果使用localtime而不是gmtime的话,则和北京时间相同。
localtime():
函数定义:struct tm *localtime(const time_t *clock);
函数说明:localtime是 把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,而gmtime函数转换后的时间没有经过时区变换,是UTC时间 。
mktime():
函数原型:time_t mktime(struct tm *timeptr);
函数说明:mktime()用来将参数timeptr所指的tm结构数据转换成从公元1970年1月1日0时0分0秒算起至今的UTC时间所经过的秒数。
返回值:该函数返回一个 time_t 值,该值对应于以参数传递的日历时间。如果发生错误,则返回 -1 值。
ctime():
函数原型:char *ctime(const time_t *timer)
函数说明:将time转换成字符串。字符串格式如下: Www Mmm dd hh:mm:ss yyyy 其中,Www 表示星期几,Mmm 是以字母表示的月份,dd 表示一月中的第几天,hh:mm:ss 表示时间,yyyy 表示年份。
time_t startTime,endTime; time(&startTime); cout << "time now:" << ctime(&startTime);
输出结果:
time now:Sun Nov 14 21:55:19 2021
asctime()
函数原型:char *asctime(const struct tm *timeptr)
函数说明:将tm类型的时间转换成字符串。字符串格式如下: Www Mmm dd hh:mm:ss yyyy 。
strftime() 比较实用
函数原型:size_t strftime (char* ptr, size_t maxsize, const char* format, const struct tm* timeptr )
函数说明:将tm类型time转换成自己想要格式的字符串。
总体测试程序:
#include <time.h>
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
time_t startTime,endTime;
double diffTime;
struct tm* tmTime;
time(&startTime);
sleep(5);
time(&endTime);
cout << "start time:" << ctime(&startTime) << endl;
diffTime = difftime(endTime,startTime);
cout << "end - start:" << diffTime << endl;
diffTime = difftime(startTime,endTime);
cout << "start - end:" << diffTime << endl;
tmTime = localtime(&startTime);
cout << "tmTime:" << asctime(tmTime) << endl;
char strTime[20];
strftime(strTime,20,"%Y%m%d%H%M%S",tmTime);
cout << "%Y%m%d%H%M%S time:" << strTime;
return 1;
}
返回结果:
start time:Sun Nov 14 22:19:24 2021
end - start:5
start - end:-5
tmTime:Sun Nov 14 22:19:24 2021
%Y%m%d%H%M%S time:20211114221924