首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么struct中的tm_year成员相对于1900,而不是1970在macosx上的C中呢?

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

Stack Overflow用户
提问于 2017-07-27 15:46:51
回答 2查看 11.6K关注 0票数 5

当我遇到这个问题时,我正在试验C专家编程中的例子。我的程序基本上做了一件事:使用标准的gmtime函数,看看1970年以来已经过去了多少年。这是我的节目:

代码语言:javascript
运行
复制
#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):

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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 。这里发生什么事情?

代码语言:javascript
运行
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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

票数 9
EN

Stack Overflow用户

发布于 2017-07-27 17:28:50

根据C库规范,tm_year成员的struct tm相对于1900。所有兼容的标准库都使用它。

tm结构应按任何顺序至少包含下列成员。成员的语义及其正常范围在注释§7.27.2.1 4中表示。

代码语言:javascript
运行
复制
...
int tm_year; // years since 1900

time()返回一个time_t值,该值“可以表示基于特定时代的日历时间”。这通常是1970年1月1日0:00的世界时间。*nix系统遵守这一原则。这个1月1日的时代,不是C所要求的,也不是连接到struct tmstruct tm成员的纪元。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45355478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档