问题描述
限时送ChatGPT账号..#include <stdio.h>
#include <time.h>
int main(int argc, char* argv[])
{
struct tm stm;
stm.tm_sec = 27;
stm.tm_min = 5;
stm.tm_hour = 18;
stm.tm_mday = 2;
stm.tm_mon = 0;
stm.tm_year = 43;
stm.tm_wday = 0;
stm.tm_yday = 0;
printf("%d\n", mktime(&stm));
getchar();
return 0;
}
打印 -1
我误解了什么?
[+edit] 这是使用带有 32 位目标的 Visual Studio 2012.我想后续问题是存储任意日期/时间值(即可能在 1900 年之前的值)的推荐方法是什么?"
[+edit] this is using Visual Studio 2012 with 32 bit target. I guess a follow up question would be 'what is the recommended method for storing arbitrary date/time values (i.e. those which may be before 1900)?'
推荐答案
在您的情况下,43 (1943) 被视为无效年份.原因是 mktime
返回一个 time_t
类型.这种类型并没有真正标准化.文档说了什么:
In you case 43 (1943) is considered as a not valid year. The reason is that mktime
return a time_t
type. This type is not really standardized. What the documentation said :
time_t
类型是一个整数值,表示自 UTC 时间 1970 年 1 月 1 日 00:00 起经过的秒数.而 tm_year 是自 1900 年以来的年数
The
time_t
type is an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC. And tm_year is the number of years since 1900
此链接time_t typedef 最终是什么? 说:
time_t
表示自 Unix 启动以来的秒数纪元:1970 年 1 月 1 日午夜 UTC(不计算闰秒).一些系统正确处理负时间值,而另一些系统做不是.
time_t
represents the number of seconds since the start of the Unix epoch: midnight UTC of January 1, 1970 (not counting leap seconds). Some systems correctly handle negative time values, while others do not.
如果我们认为 time_t
是一个有符号的 32 位整数,在最好的情况下,您可以在 ~ 13/12/1901 和 19/1/2038 之间创建日期
If we consider that time_t
is a signed 32 bits integer, in the best scenario you can create date between ~ 13/12/1901 and 19/1/2038
但是在您的情况下,实现不使用 time_t
的否定部分,因此您不能使用 mktime
创建 1970 年之前的日期.
But in your case the implementation does not use the negative part of time_t
, so you cannot create date prior 1970 with mktime
.
这篇关于当给定一个有效的 struct tm 时,mktime 返回 -1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论