当我遇到这个问题时,我正在尝试专家 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
字段在所有 POSIX 兼容平台上都是相对于 1900 的,而不仅仅是在 macOS 上。
struct tm
设计用于解析、显示和操作人类可读的日期。当它被创建时,日期通常被写入,甚至存储时没有年份数字的“19”部分,而 Y2K 问题大约在 25 年后出现。因此,通过使 tm_year
相对于 1900 年直接打印为两位数字的便利性在当时看来似乎是合理的。
Unix 时间戳是相对于“Unix 纪元”的,即 1970-01-01 00:00:00 UTC。为什么,see this Q&A .
关于c - 为什么 struct tm 中的 tm_year 成员相对于 1900 而不是 macosx 上 C 中的 1970?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45355478/