zoukankan      html  css  js  c++  java
  • (转)C语言中两种方式表示时间日期值time_t和struct tm类型的相互转换

         使用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结构数据转换成从公元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("输入的日期时间格式出错!\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;

    }

    转自 http://www.eefocus.com/xuefu2009/blog/10-04/188676_67757.html
  • 相关阅读:
    初识ambari
    MySQL Split 函数
    行存储和列存储
    Hbase安装和错误
    mysql 常用自定义函数解析
    mysq l错误Table ‘./mysql/proc’ is marked as crashed and should be repaired
    MySql提示:The server quit without updating PID file(…)失败
    mysql 自定义函数
    hive 调优总结
    [css] line boxes
  • 原文地址:https://www.cnblogs.com/woainilsr/p/2368018.html
Copyright © 2011-2022 走看看