【发布时间】:2018-01-03 11:02:26
【问题描述】:
当我遇到这个问题时,我正在尝试专家 C 编程中的示例。我的程序基本上只做一件事:使用标准的gmtime 函数,看看自 1970 年以来已经过去了多少年。
这是我的程序:
#include <stdio.h>
#include <time.h>
int main(int argc, char** argv) {
time_t now = time(0);
struct tm *t = gmtime(&now);
printf("%d\n", t->tm_year);
return 0;
}
输出为 117,即过去 1900 的年数。这是出乎意料的,因为我事先检查了time() 和man gmtime,他们都说它们是相对于纪元时间(1970-1-1 00:00:00):
time() returns the time as the number of seconds since the Epoch,
1970-01-01 00:00:00 +0000 (UTC).
The ctime(), gmtime() and localtime() functions all take an argument of data type
time_t, which represents calendar time. When interpreted as an absolute time
value, it represents the number of seconds elapsed since the Epoch, 1970-01-01
00:00:00 +0000 (UTC).
根据上面的描述,我的程序应该返回47而不是117。这是怎么回事?
macos sierra 10.12.5
Darwin 16.6.0 Darwin Kernel Version 16.6.0: Fri Apr 14 16:21:16 PDT 2017; root:xnu-3789.60.24~6/RELEASE_X86_64 x86_64
Apple LLVM version 8.1.0 (clang-802.0.42)
【问题讨论】:
-
还有手册页:
tm_year The number of years since 1900. -
您引用的 ctime(3) 联机帮助页中没有提及
tm_year。它描述了如何解释time_t值,这是gmtime(3)的参数。 -
我没有看到 C 标准对特定零日期的要求。你能提供一个参考吗?你为什么引用 OSX 的 Linux 手册页?
-
感谢所有文档和手册页:D