c/c++ 计算1900年到当前时间的秒数


常见的时间函数能获得从1970年1月1日到当前时间的秒数,这种就不多说了.

某天接到一个需求,其中一个字段的值要求取1900-01-01 00:00:00 到当前时间的秒数. 简单查了资料便写了代码,后来被测试发现时间算错了一天.于是重新整理如下:

计算逻辑:  

1900年到现在的时间 = 1970年到现在的时间 + 1900到1970年间的时间;

1970到现在的时间很容易取得,用time(time_t)就可以了(当然还有其它API可以应用)

1900到1970年间的时间是个常量:2208988800UL;

1900年~1970,共53个平年,17个闰年. 则 long long seconds = (long long)((1970 - 1900) * 365 + 17) * 24 * 60 * 60 = 2208988800;

简单示例代码如下:(vs2015+win10 64位)

#include <time.h> 
#include <stdio.h> 

int main()
{
    int a = 24, b = 60;
    //long long seconds = ((1970 - 1900) * 365 + 17) * a * b * b;    //不加强制转换结果异常
    //long long seconds = ((1970 - 1900) * 365 + 17) * 24 * 60 * 60;    //warning C4307: “*”: 整型常量溢出
    long long seconds = (long long)((1970 - 1900) * 365 + 17) * 24 * 60 * 60;
    
    //double seconds = (double)((1970 - 1900) * 365 + 17) * 24 * 60 * 60;
    //long long seconds = 2208988800;    //or double
    time_t t;
    t = time(NULL);

    printf("seconds since is %ld\nseconds of 1900~1970 is %lf\nseconds from 1900 to now is %lf\n", (long )t, seconds , t + seconds);
    return 0;
}

巨人的肩膀:

https://www.aliyun.com/jiaocheng/537945.html

https://blog.csdn.net/luck_gg/article/details/3110506


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM