由于工作的需要,对时间函数使用的比较多, 整理如下:
clock_t:这是一个适合存储处理器时间的类型。
time_t is:这是一个适合存储日历时间类型。
struct tm:这是一个用来保存时间和日期的结构。
struct tm {
int tm_sec; /* 秒,范围从 0 到 59 */
int tm_min; /* 分,范围从 0 到 59 */
int tm_hour; /* 小时,范围从 0 到 23 */
int tm_mday; /* 一月中的第几天,范围从 1 到 31 */
int tm_mon; /* 月,范围从 0 到 11 */
int tm_year; /* 自 1900 年起的年数 */
int tm_wday; /* 一周中的第几天,范围从 0 到 6 */
int tm_yday; /* 一年中的第几天,范围从 0 到 365 */
int tm_isdst; /* 夏令时
};
time_t time(time_t *timer):计算当前日历时间,并把它编码成 time_t 格式
char *ctime(const time_t *timer):返回一个表示当地时间的字符串,当地时间是基于参数 timer。
time_t mktime(struct tm *timeptr):把 timeptr 所指向的结构转换为 time_t 值。
代码示例如下:
#define _CRT_SECURE_NO_WARNINGS
#include <time.h>
#include<stdio.h>
#define TZ_TIMETH_LENG 64
typedef struct
{
int iYear; //年
int iMonth; //月
int iDay; //日
int iHour; //时
int iMin; //分
int iSecond; //秒
int iMsecond; //毫秒
}UTIL_IVMS_TIME_T;
int main()
{
time_t timep;
struct tm *info;
time(&timep); /*得到time_t类型的UTC时间*/
printf("timep:%d\n", timep);
char pTimeStr[TZ_TIMETH_LENG] = {0};
//返回本地时间的tm
info = localtime(&timep);
sprintf(pTimeStr,"%4d-%2d-%2dT%2d:%2d:%2dZ",info->tm_year+1900,info->tm_mon+1,info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
printf("pTimeStr:%s\n", pTimeStr);
UTIL_IVMS_TIME_T pstruTime;
sscanf(pTimeStr, "%4d-%2d-%2dT%2d:%2d:%2dZ", &pstruTime.iYear, &pstruTime.iMonth, &pstruTime.iDay,
&pstruTime.iHour, &pstruTime.iMin, &pstruTime.iSecond);
pstruTime.iMsecond = 0;
struct tm struTm={0};
struTm.tm_year=pstruTime.iYear - 1900;
struTm.tm_mon=pstruTime.iMonth - 1;
struTm.tm_mday=pstruTime.iDay;
struTm.tm_hour=pstruTime.iHour;
struTm.tm_min=pstruTime.iMin;
struTm.tm_sec=pstruTime.iSecond;
//返回的是UTC时间
time_t timeStamp = mktime(&struTm);
printf("timeStamp:%d\n", timeStamp);
printf("dur:%d\n", (timeStamp-timep)/3600);
struct tm *p;
p = gmtime(&timep); /*得到tm结构的UTC时间*/
sprintf(pTimeStr,"%4d-%2d-%2dT%2d:%2d:%2dZ",info->tm_year+1900,info->tm_mon+1,info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
printf("pTimeStr:%s\n", pTimeStr);
sscanf(pTimeStr, "%4d-%2d-%2dT%2d:%2d:%2dZ", &pstruTime.iYear, &pstruTime.iMonth, &pstruTime.iDay,
&pstruTime.iHour, &pstruTime.iMin, &pstruTime.iSecond);
pstruTime.iMsecond = 0;
struTm.tm_year=pstruTime.iYear - 1900;
struTm.tm_mon=pstruTime.iMonth - 1;
struTm.tm_mday=pstruTime.iDay;
struTm.tm_hour=pstruTime.iHour;
struTm.tm_min=pstruTime.iMin;
struTm.tm_sec=pstruTime.iSecond;
//返回的是UTC时间
timeStamp = mktime(&struTm);
printf("timeStamp:%d\n", timeStamp);
printf("dur:%d\n", (timeStamp-timep)/3600);
return 0;
}
运行结构:
注意事项:
1.mktime有时区转化
2.time():返回的是UTC时间
参考文献:
https://www.runoob.com/cprogramming/c-standard-library-time-h.html
https://www.runoob.com/w3cnote/cpp-time_t.html