2016-12-25 39 views
-6

我有這樣的代碼:爲什麼年份會在C中返回116而不是2016年?

#include <stdio.h> 
#include <time.h>  

int main(void) { 

    time_t rawtime = time(NULL); 
    struct tm *ptm = localtime(&rawtime); 
    printf("The time is: %02d:%02d:%02d\n", ptm->tm_hour, 
      ptm->tm_min, ptm->tm_sec); 
    printf("The date is: %02d:%02d:%04d\n.", ptm->tm_mday, ptm->tm_mon, ptm->tm_year); 
    return 0; 
} 

當我運行它,它返回的tm_year爲116,而不是2016年的價值誰能告訴我爲什麼?自1900年以來

+6

您是否嘗試過閱讀的文檔?什麼'tm_year'存儲? –

+0

@ n.m。它已在庫timeh中聲明如下: struct tm { int \t tm_sec; int \t tm_min; int \t tm_hour; int \t tm_mday; int \t tm_mon; int \t tm_year; int \t tm_wday; int \t tm_yday; int \t tm_isdst; –

+4

請仔細閱讀[手冊](https://linux.die.net/man/3/localtime) –

回答

3

tm_year場被表示爲年:https://linux.die.net/man/3/localtime

+0

對不起,但我沒有得到你所說的。你可以說得更詳細點嗎? –

+0

@ A.Pearce - 請解釋你不明白的部分 –

+3

我怎麼能比這更具體?該字段的定義是自1900年以來的年數。自2016年以來,2016 - 1900年爲116年。 – ra4king

2

由於tm_year是自1900年以來的年數,你需要添加1900本。

來源:http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html

所以,你得到:

#include <stdio.h> 
#include <time.h> 

int main(void) { 

    time_t rawtime = time(NULL); 
    struct tm *ptm = localtime(&rawtime); 
    printf("The time is: %02d:%02d:%02d\n", ptm->tm_hour, 
      ptm->tm_min, ptm->tm_sec); 
    printf("The date is: %02d:%02d:%04d\n.", ptm->tm_mday, ptm->tm_mon, ptm->tm_year+1900); 
    return 0; 
} 
相關問題