gpt4 book ai didi

c - printf epochtime 显示错误的值

转载 作者:行者123 更新时间:2023-12-04 08:39:32 24 4
gpt4 key购买 nike

我正在试验 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变量,但它们似乎都不适合我。任何想法为什么?

最佳答案

我假设您要表示的日期是:2002 年 10 月 19 日 00:00:00,它对应于您期望的纪元时间戳:1034985600。
在这种情况下,你做错了。阅读 the manual :

Broken-down time is stored in the structure tm, which is defined in <time.h> as follows:

struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};

你的年份应该是 2002 - 1900 = 102,你的月份应该是 9,而不是 10(月份从 0 = 一月开始)。
正确的代码是:
#include <stdio.h>
#include <time.h>
#include <inttypes.h>

int main(void) {
struct tm epochtime = {
.tm_mday = 19,
.tm_mon = 9,
.tm_year = 102,
.tm_hour = 0,
.tm_min = 0,
.tm_sec = 0,
.tm_isdst = -1
};

time_t epochdate = mktime(&epochtime);
if (epochdate == (time_t)(-1)) {
perror("mktime failed");
return 1;
}

printf("%" PRIuMAX "\n", (uintmax_t)epochdate);
return 0;
}
哪个正确输出 1034985600如你所料。
您的代码的问题很可能是 mktime无法正确表示您提供的“错误”日期并返回 -1 ,然后您将其打印为无符号并成为一个巨大的无意义数字。

关于c - printf epochtime 显示错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64630721/

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