[英]Why is the year value in Perl's localtime function (and C's tm struct) relative to 1900?
[英]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).
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).
根據上面的描述,我的程序應該返回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 tm
的tm_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 tm
的tm_year
成員的時期沒有直接的tm_year
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.