【发布时间】:2021-02-14 05:38:05
【问题描述】:
我正在试验time_t 变量,这是有问题的代码:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
struct tm epochtime;
time_t epochdate;
int main()
{
epochtime.tm_mday = 19;
epochtime.tm_mon = 10;
epochtime.tm_year = 2002;
epochtime.tm_hour = 0;
epochtime.tm_min = 0;
epochtime.tm_sec = 0 ;
epochdate = mktime(&epochtime);
printf("%ju\n",epochdate);
printf("%ju\n", (uint32_t)epochdate);
printf("%ju\n", (uint64_t)epochdate);
printf("%ju\n", (uintmax_t)epochdate);
printf("%Lf\n", epochdate);
printf("%Le\n", epochdate);
}
我正在尝试打印给定日期的epochtime。代码可以编译并且没有错误,但是当我将打印的内容与我在this website 上计算的内容进行比较时,这些值并不相同。对于上面示例中的给定值,代码输出为:
210453397503
210453397503
18446744073709551615
18446744073709551615
-1.#QNAN0e+000
-1.#QNAN0e
虽然链接说该值应该是1034985600。我尝试了多个 printf 格式说明符,因为我在这里找到了有关如何打印 time_t 变量的多个答案,但它们似乎都不适合我。任何想法为什么?
【问题讨论】:
-
18446744073709551615是(uint64_t)-1... 显然你的mktime()正在返回-1: C11 7.27.2.3 -- "如果无法表示日历时间,则函数返回值 (time_t )(-1)。” -
也许您需要将年份(1900 年前)和月份(1 个月前)移位,...并注意 DST?
-
第一步应该始终是手册页:"
tm_year年份(当前年份减去 1900)。" -
@pmg 这个月,我在计算时牢记 -1 转变。我查看了 struct tm 的确切定义,我没有指定那一年的链接是从 1900 年开始计算的。顺便说一句,你的建议奏效了,谢谢!
-
在
printf("%ju\n", (uint32_t)epochdate);中,j告诉printf你正在传递类型uintmax_t但你不是 - 它是uint32_t所以也是 未定义的行为 .请参阅Format specification syntax: printf。
标签: c format-specifiers time-t