#include <time.h>
原型:
time_t time(time_t *t)
time_t的定义:
typedef __darwin_time_t time_t;
typedef long __darwin_time_t;
返回值:UTC(coordinated universal time)时间1970年1月1日00时00分00秒(也称为Linux系统的Epoch时间)到当前时刻的秒数
例:1
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time(NULL);
printf("自 1970-01-01 起的小时数 = %ld\n", seconds/3600);
return(0);
}
二、localtime localtime_r
头文件:
#include <time.h>
原型:
struct tm *localtime(const time_t *timep)
原型:
struct tm *localtime_r(const time_t *timep, struct tm *result);
结构体tm
struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
/* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
};
localtime 与 localtime_r区别
localtime 不是可重入 localtime_r 可重入
例2:
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
time_t tNow =time(NULL);
time_t tEnd = tNow + 1800;
//注意下面两行的区别
struct tm* ptm = localtime(&tNow);
struct tm* ptmEnd = localtime(&tEnd);
char szTmp[50] = {0};
strftime(szTmp,50,"%H:%M:%S",ptm);
char szEnd[50] = {0};
strftime(szEnd,50,"%H:%M:%S",ptmEnd);
printf("%s/n",szTmp);
printf("%s/n",szEnd);
return 0;
}
最后出来的结果是:
20:30:32
20:30:32
例3:
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
time_t tNow =time(NULL);
time_t tEnd = tNow + 1800;
struct tm ptm = { 0 };
struct tm ptmEnd = { 0 };
localtime_r(&tNow, &ptm);
localtime_r(&tEnd, &ptmEnd);
char szTmp[50] = {0};
strftime(szTmp,50,"%H:%M:%S",&ptm);
char szEnd[50] = {0};
strftime(szEnd,50,"%H:%M:%S",&ptmEnd);
printf("%s\n",szTmp);
printf("%s\n",szEnd);
return 0;
}
最后出来的结果是:
20:03:21
20:33:21
三、gettimeofday
头文件:
#include <sys/time.h>
原型:
int gettimeofday(struct timeval*tv, struct timezone *tz)
tv:是保存获取时间结果的结构体
struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
tz:用于保存时区结果
struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST 时间的修正方式*/
}
返回值:成功返回0,失败返回-1,错误代码保存于errno中
四、mktime
头文件:
#include <time.h>
原型:
time_t mktime(struct tm *tm)
返回值:1970年1月1日以来持续时间的秒数,发生错误时返回-1。
例4:
#include<stdio.h>
#include<time.h>
int main(void)
{
time_t timep;
struct tm* p;
time(&timep);
printf("time():%d\n",timep);
p=localtime(&timep);
timep=mktime(p);
printf("time()->localtime()->mktime():%d\n",timep);
return 0;
}
输出:
time():1541246772
time()->localtime()->mktime():1541246772