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

来源:互联网 发布:天下3捏脸数据女 编辑:程序博客网 时间:2024/04/29 17:23
#include <iostream>#include <time.h>using namespace std;int main(){    time_t t;    struct tm Tm;    clock_t clBegin = clock();    for (int i = 0; i < 100; i++)    {        _sleep(1);    }    clock_t clEnd = clock();    clock_t diff = clEnd - clBegin;    cout<<"从开始到现在占用CPU的时间差(单位 毫秒):"<<diff<<endl;    t = time(0);                        //获取当前日历时间,即为从1970年1月1日开始经历的秒数,到2016年11月8日大概是1478591635s    Tm = *localtime(&t);                //日历时间转换为当地时间    cout<<"一年中天数:"<<Tm.tm_yday<<endl;    cout<<"一月中天数:"<<Tm.tm_mday<<endl;    cout<<"一周中天数:"<<Tm.tm_wday<<endl;    cout<<"小时:"<<Tm.tm_hour<<endl;    cout<<"分钟:"<<Tm.tm_min<<endl;    cout<<endl;    Tm = *gmtime(&t);                   //日历时间转换为协调世界时(UTC)    cout<<"一年中天数:"<<Tm.tm_yday<<endl;    cout<<"一月中天数:"<<Tm.tm_mday<<endl;    cout<<"一周中天数:"<<Tm.tm_wday<<endl;    cout<<"小时:"<<Tm.tm_hour<<endl;    cout<<"分钟:"<<Tm.tm_min<<endl;    system("date");    return 0;}

使用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函数返回当前时区的时间,
1 转换日期时间表示形式time_t类型转换为structtm类型示例:

int main(){   char*wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};/*指针字符数组*/   time_t t;   struct tm *p;   t=time(NULL);/*获取从1970年1月1日零时到现在的秒数,保存到变量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);则返回当前时区的时间

2 使用mktime函数将structtm类型的时间日期转换为time_t类型:
表头文件
定义函数

time_t mktime(strcut tm *timeptr);

函数说明
mktime()用来将参数timeptr所指的tm结构数据转换成从公元1970年1月1日0时0分0 秒算起至今的UTC时间所经过的秒数。
返回值
返回经过的秒数。

日期转换为秒数示例:

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;}
0 0