【问题标题】:C: add days to dates OS-independent, before 1970C:在 1970 年之前的日期中添加天数,与操作系统无关
【发布时间】:2019-09-09 21:34:58
【问题描述】:

我想使用mktime 为我的约会添加天数。代码取自here,tm 结构初始化取自here。这段代码在 Linux (gcc) 上运行:

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

int main(int argc, char **argv)
{
    struct tm t = { 0 };
    t.tm_mday += 40;
    time_t try1 = mktime(&t);
    /* show result */
    printf("%d %d %d %d %s", t.tm_year, t.tm_mon, t.tm_mday, try1, ctime(&try1));
    return 0;
}

程序预期返回:0 1 9 2089348096 Fri Feb 9 00:00:00 1900

但是,当我在 Windows 上使用

编译相同的代码时

GNU C11(Rev4,由 MSYS2 项目构建)版本 5.2.0 (x86_64-w64-mingw32) 由 GNU C 版本 5.2.0、GMP 版本 6.0.0、MPFR 版本 3.1.3、MPC 版本 1.0.3 编译

我得到这个输出:0 0 40 -1 (null)

如何在 Windows 上为日期添加天数?

更新。事实证明,Windows 上的 mktime 仅在生效日期在 1970 年 1 月 1 日之后才有效。搞笑。这是一个小例子:

int main(int argc, char **argv)
{
    struct tm t = { 0 };
    t.tm_year = 70;
    t.tm_mday = 1;

    t.tm_mday += 40;
    time_t try1 = mktime(&t);
    /* show result */
    printf("%d %d %d %d %s", t.tm_year, t.tm_mon, t.tm_mday, try1, ctime(&try1));
    return 0;
}

MS Docs:

_mkgmtime32 函数的范围是从 UTC 时间 1970 年 1 月 1 日午夜到 UTC 时间 2038 年 1 月 18 日 23:59:59。 _mkgmtime64 的范围是从 UTC 时间 1970 年 1 月 1 日午夜到 UTC 时间 3000 年 12 月 31 日 23:59:59。超出范围的日期会导致返回值 -1。 _mkgmtime 的范围取决于是否定义了 _USE_32BIT_TIME_T。如果未定义(默认),则范围为 _mkgmtime64;否则,范围被限制在 _mkgmtime32 的 32 位范围内。

问题仍然存在。有没有办法在独立于操作系统的日期上添加天数?最好不限于 1970 年 1 月 1 日之后。

【问题讨论】:

  • Windows 不是唯一使用 Unix 纪元作为 time_t 值和时间处理基础的操作系统。以便携的方式处理日期/时间计算比您想象的要很多复杂。

标签: c windows mingw mingw-w64 mktime


【解决方案1】:
void second_calculate()
{

    //47 year       ------>1970+47=2017
    //12 day        ------>12 leap year   29 february!!
    //test=0        ------> 00:00:00 01.01.1970   

    int _sec = 1;
    int _min = 60;
    int _hour = 60 * 60;
    int _day = 24 * 60 * 60;
    int _year = 365 * 24 * 60 * 60;


    long long test = 
        47   * _year            //  1970 +47  ---->  2017 
        + 12 * _day             //  leap year ---->  47/4 
        + 40 * _day             //  new year +40 day ---->  february 10
        + 22 * _hour            //  evening  22:00:00 
           +0* _min             //  
           +0* _sec;            //  



    //grennwich
    tm* ptm3 = gmtime(&test);
    printf("date: %s\n", asctime(ptm3));    //22:00:00 10.02.2017 


}

【讨论】:

    猜你喜欢
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    相关资源
    最近更新 更多