gpt4 book ai didi

C:在 1970 年之前添加与操作系统无关的日期

转载 作者:行者123 更新时间:2023-11-30 16:18:54 25 4
gpt4 key购买 nike

我想使用 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, Built by MSYS2 project) version 5.2.0 (x86_64-w64-mingw32) compiled by GNU C version 5.2.0, GMP version 6.0.0, MPFR version 3.1.3, MPC version 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 :

The range of the _mkgmtime32 function is from midnight, January 1, 1970, UTC to 23:59:59 January 18, 2038, UTC. The range of _mkgmtime64 is from midnight, January 1, 1970, UTC to 23:59:59, December 31, 3000, UTC. An out-of-range date results in a return value of -1. The range of _mkgmtime depends on whether _USE_32BIT_TIME_T is defined. If not defined (the default) the range is that of _mkgmtime64; otherwise, the range is limited to the 32-bit range of _mkgmtime32.

问题仍然存在。有没有什么方法可以独立于操作系统添加日期?最好不限于 1970 年 1 月 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


}

关于C:在 1970 年之前添加与操作系统无关的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com