当我遇到这个问题时,我正在试验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
,他们都说它们是相对于Epoch时间(1970-1-1 00: 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)
发布于 2017-07-27 16:25:26
tm_year
字段相对于所有POSIX兼容平台上的1900,而不仅仅是在macOS上。
struct tm
用于分析、显示和操作人类可读的日期.当它被创建时,日期通常被写入,甚至没有年份号的“19”部分而存储,而Y2K问题大约在25年后出现。因此,将tm_year
直接打印为两位数,相对于1900年而言,其方便性在当时看来似乎是合理的。
Unix时间戳是相对于“Unix时代”的,即1970-01-01 : 00:00:00。因为原因,see this Q&A。
发布于 2017-07-27 17:28:50
根据C库规范,tm_year
成员的struct tm
相对于1900。所有兼容的标准库都使用它。
tm
结构应按任何顺序至少包含下列成员。成员的语义及其正常范围在注释§7.27.2.1 4中表示。
...
int tm_year; // years since 1900
time()
返回一个time_t
值,该值“可以表示基于特定时代的日历时间”。这通常是1970年1月1日0:00的世界时间。*nix系统遵守这一原则。这个1月1日的时代,不是C所要求的,也不是连接到struct tm
的struct tm
成员的纪元。
https://stackoverflow.com/questions/45355478
复制相似问题