代码之家  ›  专栏  ›  技术社区  ›  Rainbow Fizz

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

  •  5
  • Rainbow Fizz  · 技术社区  · 7 年前

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

    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)
    
    2 回复  |  直到 7 年前
        1
  •  8
  •   rob mayoff    7 年前

    tm_year 字段相对于1900开 兼容POSIX的平台,而不仅仅是在macOS上。

    这个 struct tm 用于解析、显示和操作人类可读的日期。当它被创建时,日期通常是写出来的,甚至没有年份数字的19部分来存储,而Y2K问题大约还有25年。所以制作的便利性 tm_年 直接打印为两位数,相对于1900,在当时似乎是合理的。

    Unix时间戳相对于Unix纪元,即1970-01-01 00:00:00 UTC。原因是, see this Q&A

        2
  •  1
  •   chux    7 年前

    这个 tm_year struct tm 相对于C库规范中的1900。所有符合标准的库都使用该功能。

    这个 tm

    ...
    int tm_year; // years since 1900
    

    time() 返回a time_t 值”,可能代表 tm_年 成员 .