概述
本历程都是Linux下关于时间计算函数使用,基准时间为 1970-01-01 00:00:00 +0000(UTC)
注意xx与xx_r的使用方式,涉及到可重入与不可重入函数的使用
正文
函数time(获取秒数)
函数原型
time_t time(time_t *t);
参数
参数t是把time获取的秒数存到地址处
返回值
返回时间(s)
函数ctime(由秒数获取字符串时间)
函数原型
char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);
参数
参数timep为秒数的地址
参数buf为需要存储字符串地址
返回值
字符串地址
函数asctime(由结构体获取字符串)
函数原型
char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);
参数
参数tm为需要转换的结构体地址
参数buf为需要存储字符串地址
返回值
字符串地址
函数strftime(按特定格式 输出字符串时间)
函数原型
size_t strftime(char *s, size_t max, const char *format,const struct tm *tm);
参数
参数s为存入的数组地址
参数max为存入的数组大小
参数format为需要输出的格式
参数tm为需要转换的时间结构体
返回值
函数gmtime(国际时间)
函数原型
struct tm *gmtime(const time_t *timep);
struct tm *gmtime_r(const time_t *timep, struct tm *result);
参数
参数timep为需要转换的秒数
参数result为转换后的结构体地址
返回值
转换后的结构体地址
函数localtime(本地时间)
函数原型
struct tm *localtime(const time_t *timep);
struct tm *localtime_r(const time_t *timep, struct tm *result);
参数
参数timep为需要转换的秒数
参数result为转换后的结构体地址
返回值
转换后的结构体地址
函数mktime(把具体时间转换为秒数)
函数原型
time_t mktime(struct tm *tm);
参数
参数tm为需要转换的结构体地址
返回值
转换好的秒数
测试代码
int main(void)
{
time_t Mytime_t = 0;
char buf[30] = {0};
time(&Mytime_t); /*获取当前时间的秒数,以1970-01-01 00:00:00 +0000(UTC)为基准*/
if(Mytime_t < 0)
{
perror("time ");
return -1;
}
printf("Mytime_t = %ld\r\n",Mytime_t);
ctime_r(&Mytime_t,buf); /*把秒转换为字符串*/
printf("ctime_r = %s\r\n",buf);
struct tm localtm,gmtm;
memset(&localtm,0,sizeof(localtm));
memset(&gmtm,0,sizeof(gmtm));
localtime_r(&Mytime_t,&localtm);/*把秒转换为结构体,当地时间*/
gmtime_r(&Mytime_t,&gmtm);/*把秒转换为结构体,国际时间*/
asctime_r(&localtm,buf);/*把当地时间结构体转换为字符串*/
printf("asctime_r localtm = %s\r\n",buf);
asctime_r(&gmtm,buf);/*把国际时间结构体转换为字符串*/
printf("asctime_r gmtm = %s\r\n",buf);
strftime(buf,30,"%Y * %m * %d, %H-%M-%S.",&localtm);/* 年*月*日 时-分-秒*/
printf("strftime localtm = %s\r\n",buf);
strftime(buf,30,"%Y * %m * %d, %H-%M-%S.",&gmtm);/* 年*月*日 时-分-秒*/
printf("strftime gmtm = %s\r\n",buf);
/*************************************************/
struct tm Mymktime;
time_t Mytime_t2 = 0;
memset(&Mymktime,0,sizeof(Mymktime));
Mymktime.tm_sec = 55;
Mymktime.tm_min = 49;
Mymktime.tm_hour = 15;
Mymktime.tm_mday = 30;
Mymktime.tm_mon = 5 - 1;
Mymktime.tm_year = 2017 - 1900;
Mytime_t2 = mktime(&Mymktime);/*把2017/05/30 15:49:55转换为秒数*/
printf("Mytime_t2 = %ld\r\n",Mytime_t2);
return 0;
}
参考
参考朱友鹏Linux教程资料