簡體   English   中英

為什么在macosx上struct tm中的tm_year成員相對於1900而不是1970中的1970?

[英]Why is the tm_year member in struct tm relative to 1900 rather than 1970 in C on macosx?

遇到此問題時,我正在嘗試使用專家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)

所有 POSIX兼容平台上,不僅在macOS上, tm_year字段都相對於1900。

struct tm設計用於解析,顯示和處理人類可讀的日期。 創建日期時,通常會寫日期,甚至存儲日期時也不會包含年份數字中的“ 19”部分,並且距Y2K問題大約還有25年的距離。 因此,使tm_year相對於1900成為直接可兩位數打印的便利,在當時似乎很合理。

Unix時間戳相對於“ Unix紀元”,即1970-01-01 00:00:00 UTC。 出於這個原因, 請參閱此問答

根據C庫規范, struct tmtm_year成員相對於1900。 所有符合標准的庫都使用該庫。

tm結構至少應按任何順序包含以下成員。 成員的語義及其正常范圍在第7.27.2.1條注釋中表示4

...
int tm_year; // years since 1900

time()返回time_t值“可以表示基於特定紀元的日歷時間”。 這通常是世界標准時間1970年1月1日0:00:00。 * nix系統堅持這一點。 C不需要1月1日這一時期,並且與struct tmtm_year成員的時期沒有直接的tm_year

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM