2017-07-27 31 views
-1

我正在尝试使用专家C编程中的示例,同时遇到此问题。我的程序基本上是做一件事情:使用标准gmtime功能,看看有多少岁月已经过去自1970年以来 这里是我的程序:为什么结构tm中的tm_year成员相对于1900年而不是1970年的macosx上的C?

#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; 
} 

输出为,几年过去数。这是出乎意料的,因为我查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

根据以上描述,我的程序应该返回而不是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

因为这就是[doc说](http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html)也是[在线手册](http://www.cplusplus。com/reference/ctime/tm /) – litelite

+1

另外手册页:'tm_year 1900年以来的年数.' – Mat

+0

您引用的ctime(3)手册页的部分没有提及有关'tm_year'的任何内容。它描述了如何解释'time_t'的值,它是'gmtime(3)'的*参数*。 – Ssswift

回答

2

tm_year场是相对于1900的所有 POSIX兼容的平台,而不仅仅是在MacOS。

struct tm专为解析,显示和操作人类可读的日期而设计。创建日期时,通常会编写日期,甚至不存储年份编号中的“19”部分,而2000年的Y2K问题需要大约25年。因此,使tm_year可以直接打印成两位数的方便性,通过使其相对于1900,显然在当时似乎是合理的。

Unix时间戳相对于“Unix时代”,即1970-01-01 00:00:00 UTC。为什么,see this Q&A

+0

谢谢你的答案!我的Mac上的'/ usr/include/time.h'页面显示它的确相对于1900. –

0

tm_year成员相对于每个C库规范1900。所有符合标准的库都使用它。

tm结构应至少包含以下任意顺序的成员。成员及其正常范围的语义评价§7.27.2.14

... 
int tm_year; // years since 1900 

time()返回time_t值“其可以表示基于特定时期一个 日历时间”表示。这通常是1970年1月1日0:00:00世界时。 * nix系统坚持这一点。这个1月1号的时代不是C所要求的,并且不直接连接到成员struct tm的时代。

+0

我明白了。所以'struct tm'由C标准定义,并且与* nix约定没有关系。 –

+0

@RainbowFizz'time_t'也由C标准库定义。它是C标准允许各种实现细节,例如什么日期/时间是'(time_t)0'。许多'nix'编译器进一步以通用的方式限制这些细节,比如1970年1月1日拥有'(time_t)0'。 – chux

相关问题