c - 为什么 struct tm 中的 tm_year 成员相对于 1900 而不是 macosx 上 C 中的 1970?

标签 c macos time.h

当我遇到这个问题时,我正在尝试专家 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).

http://man7.org/linux/man-pages/man2/time.2.html

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).

http://man7.org/linux/man-pages/man3/ctime.3.html

根据上面的描述,我的程序应该返回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/

相关文章:

c++ - iOS — 确定 Accelerate.framework 在运行时是否可用

c++ - 在 unix 中编译 dhrystone 时出错

c - 随机数生成代码不起作用[可能是堆栈溢出]

c - printf 上错误的 clock_t 输出值

macos - 在 Mac OS X 中将所有窗口移动到单个监视器(连接两个)?

c - 打印两个值中的最高值而不使用 if 语句

c - 一个C代码的Delphi等效代码

linux - 当您没有权限时在 Mac 或 Linux 上编辑 sudoers 文件

c - 无法编译 pjsua 二进制文件