【问题标题】:Why does year return 116 instead of 2016 in C?为什么年份在 C 中返回 116 而不是 2016?
【发布时间】:2016-12-25 10:15:30
【问题描述】:

我有这个代码:

#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。谁能告诉我为什么?

【问题讨论】:

  • 您是否尝试过阅读文档? tm_year 存储什么?
  • @n.m.它已在库 time.h 中声明如下: struct tm { int tm_sec;诠释 tm_min;诠释 tm_hour;诠释 tm_mday;诠释 tm_mon;诠释 tm_year; int tm_wday; int tm_yday; int tm_isdst;
  • 请阅读manual
  • 对不起,我问这个问题时有点粗心@@我的坏
  • 你应该阅读文档而不是实现。该实现告诉您 tm_year 存储了一些整数。下一步是什么?

标签: c date time.h


【解决方案1】:

tm_year 字段表示为自 1900 年以来的年份:https://linux.die.net/man/3/localtime

【讨论】:

  • 对不起,我不明白你说什么。你能说得更具体点吗?
  • @A.Pearce - 请说明您不理解的部分
  • 我怎么能比这更具体?该字段被简单地定义为自 1900 年以来的年数。因为年份是 2016 年,所以 2016 - 1900 = 116。
  • 编辑:对不起,我明白你的意思了
【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2022-12-16
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    相关资源
    最近更新 更多