time_t 和 tm 结构体

来源:互联网 发布:淘宝宁夏中宁枸杞 编辑:程序博客网 时间:2024/04/30 20:34

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

使用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类型转换为struct tm类型示例:

#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\n", p->tm_hour, p->tm_min, p->tm_sec);

    return 0;

}

 

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

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

表头文件

#include

定义函数

time_t mktime(strcut tm * timeptr);

函数说明

mktime()用来将参数timeptr所指的tm结构数据转换成从公元19701100秒算起至今的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("输入的日期时间格式出错!\n");

        exit(1);

}

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

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

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

    return 0;

}

 

time()函数获取日历时间

我们可以通过time()函数来获得日历时间(Calendar Time),其原型为:time_t time(time_t * timer); 
如果你已经声明了参数timer,你可以从参数timer返回现在的日历时间,同时也可以通过返回值返回现在的日历时间,即从一个时间点(例如:1970 年1月1日0时0分0秒)到现在此时的秒数。如果参数为空(NULL),函数将只通过返回值返回现在的日历时间,比如下面这个例子用来显示当前的日历时间:

#include "time.h" 
#include "stdio.h" 
int main(void) 

struct  tm  *ptr; 
time_t  lt; 
lt = time(NULL); 
printf("The Calendar Time now is %d\n",lt); 
return 0; 


运行的结果与当时的时间有关,我当时运行的结果是:

The Calendar Time now is 1122707619 

0 0