zoukankan      html  css  js  c++  java
  • C++时间戳转化(涉及GMT CST时区转化)

    问题由来

    时间戳转换(时间戳:自 1970 年1月1日(00:00:00 )至当前时间的总秒数。)

    #include <stdio.h>
    #include <time.h>
    
    int main(int argc, const char * argv[])
    {    
        time_t t;
        struct tm *p;
        t=1408413451;
        p=gmtime(&t);
        char s[80];
        strftime(s, 80, "%Y-%m-%d %H:%M:%S", p);
        printf("%d: %s
    ", (int)t, s);
    }

    结果

    1408413451      2014-08-19 01:57:1408384651
    

    可是利用命令在linux终端计算的结果不一

    [###t]$ date -d @1408413451
    Tue Aug 19 09:57:31 CST 2014
    

    通过比较发现,两者正好差8个小时,CST表示格林尼治时间,通过strftime()函数可以输出时区,改正如下

    #include <stdio.h>
    #include <time.h>
    
    int main(int argc, const char * argv[])
    {    
        time_t t;
        struct tm *p;
        t=1408413451;
        p=gmtime(&t);
        char s[80];
        strftime(s, 80, "%Y-%m-%d %H:%M:%S::%Z", p);
        printf("%d: %s
    ", (int)t, s);
    }

    结果

    1408413451: 2014-08-19 01:57:31::GMT
    

    深究

    GMT(Greenwich Mean Time)代表格林尼治标准时间。十七世纪,格林威治皇家天文台为了海上霸权的扩张计画而进行天体观测。1675年旧皇家观测所正式成立,通过格林威治的子午线作为划分地球东西两半球的经度零度。观测所门口墙上有一个标志24小时的时钟,显示当下的时间,对全球而言,这里所设定的时间是世界时间参考点,全球都以格林威治的时间作为标准来设定时间,这就是我们耳熟能详的「格林威治标准时间」(Greenwich Mean Time,简称G.M.T.)的由来。

    CST却同时可以代表如下 4 个不同的时区:

    Central Standard Time (USA) UT-6:00
    Central Standard Time (Australia) UT+9:30
    China Standard Time UT+8:00
    Cuba Standard Time UT-4:00
    

    可见,CST可以同时表示美国,澳大利亚,中国,古巴四个国家的标准时间。

    好了两者差8个小时(CST比GMT晚/大8个小时),GMT+8*3600=CST,代码如下

    #include <stdio.h>
    #include <time.h>
    
    int main(int argc, const char * argv[])
    {    
        time_t t;
        struct tm *p;
        t=1408413451;
        p=gmtime(&t);
        char s[80];
        strftime(s, 80, "%Y-%m-%d %H:%M:%S::%Z", p);
        printf("%d: %s
    ", (int)t, s);
    
        t=1408413451 + 28800;
        p=gmtime(&t);
        strftime(s, 80, "%Y-%m-%d %H:%M:%S", p);
        printf("%d: %s
    ", (int)t, s);
        return 0;
    }

    结果

    1408413451: 2014-08-19 01:57:31::GMT
    1408442251: 2014-08-19 09:57:31
    

    linux平台

    Tue Aug 19 09:57:31 CST 2014
    

      

  • 相关阅读:
    javascript 判断电话号码的格式
    JavaScript 'Pig latin is cool'==>'igPay atinlay siay oolcay'
    JavaScript 找出特殊数字如135 = 1^1 + 3^2 + 5^3
    nginx+Apache实现动静分离
    MYSQL数据库的主从复制
    Connection could not be established with host smtp.163.com [Connection timed out #110]
    Yii2 的 redis 应用
    Yii2 模块名、控制器名、方法名
    讯搜
    支付宝异步通知时间点分布
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3922919.html
Copyright © 2011-2022 走看看