C语言中两种方式表示时间日期值time_t和struct tm类型的相互转换

使用gmtime函数或localtime函数将time_t类型的时间日期转换为structtm类型:

使用time函数返回的是一个long值,该值对用户的意义不大,一般不能根据其值确定具体的年、月、日等数据。gmtime函数可以方便的对time_t类型数据进行转换,将其转换为tm结构的数据方便数据阅读。

gmtime函数的原型如下:

struct tm *gmtime(time_t*timep);

localtime函数的原型如下:

struct tm *localtime(time_t*timep);

将参数timep所指的time_t类型信息转换成实际所使用的时间日期表示方法,将结果返回到结构tm结构类型的变量。

gmtime函数用来存放实际日期时间的结构变量是静态分配的,每次调用gmtime函数都将重写该结构变量。如果希望保存结构变量中的内容,必须将其复制到tm结构的另一个变量中。

gmtime函数与localtime函数的区别:

gmtime函数返回的时间日期未经时区转换,是UTC时间(又称为世界时间,即格林尼治时间)

localtime函数返回当前时区的时间,

转换日期时间表示形式time_t类型转换为structtm类型示例:

#include

#include

int main()

{

    char*wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};/*指针字符数组*/

   time_t t;

   struct tm *p;

   t=time(NULL);/*获取从197011日零时到现在的秒数,保存到变量t*/

   p=gmtime(&t); /*变量t的值转换为实际日期时间的表示格式*/

   printf("%d%02d%02d",(1900+p->tm_year),(1+p->tm_mon),p->tm_mday);

   printf(" %s ", wday[p->tm_wday]);

printf("%02d:%02d:%02d ", p->tm_hour,p->tm_min, p->tm_sec);

    return 0;

}

 

注意:p=gmtime(&t);此行若改为p=localtime(&t);则返回当前时区的时间

     使用mktime函数将structtm类型的时间日期转换为time_t类型:

表头文件

#include

定义函数

time_t mktime(strcut tm *timeptr);

函数说明

mktime()用来将参数timeptr所指的tm结构数据转换成从公元197011000 秒算起至今的UTC时间所经过的秒数。

返回值

返回经过的秒数。

 

日期转换为秒数示例:

#include

#include

int main()

{

   time_t t;

   struct tm stm;

   printf("请输入日期时间值(yyyy/mm/dd hh:mm:ss格式)");

   scanf("%d/%d/%d%d:%d:%d",&stm.tm_year,&stm.tm_mon,&stm.tm_mday,

       &stm.tm_hour,&stm.tm_min,&stm.tm_sec);

stm.tm_year-=1900; /*年份值减去1900,得到tm结构中保存的年份序数*/

stm.tm_mon-=1;    /*月份值减去1,得到tm结构中保存的月份序数*/

t=mktime(&stm);  /* 若用户输入的日期时间有误,则函数返回值为-1*/

if(-1==t)

{

       printf("输入的日期时间格式出错! ");

        exit(1);

}

printf("1970/01/01 00:00:00~%d/%02d/%02d%02d:%02d:%02d%d ",

   stm.tm_year+1900,stm.tm_mon,stm.tm_mday,

       stm.tm_hour,stm.tm_min,stm.tm_sec,t);

   return 0;

}

转:http://www.360doc.com/content/11/0720/14/1317564_134702417.shtml

原文地址:https://www.cnblogs.com/zl-graduate/p/6061135.html