【问题标题】:Why my print current date time (C language) gives different answer为什么我的打印当前日期时间(C 语言)给出不同的答案
【发布时间】:2011-02-10 03:03:45
【问题描述】:

我想获取当前日期(日、月和年)。我发现 C 中有一些函数可以做到这一点,例如 ctime(获取时间字符串)、localtime 和 gmtime。我尝试使用以下代码,但输出不同。我得到这个输出:

日期和时间是 2010 年 4 月 20 日星期二(正确)

年份是:110

年份是:110。

有人知道为什么吗?

int main(int argc, char** argv)
{   
   time_t now;
   if((now = time(NULL)) == (time_t)-1)
   {
      puts("Failure in getting time");
   }
   else {
      printf("The date and time is: %s\n", ctime(&now));
      printf("The year is: %ld\n", localtime(&now)->tm_year);
      printf("The year is: %ld\n", gmtime(&now)->tm_year);
   }
   getchar();
}

【问题讨论】:

    标签: c datetime printf


    【解决方案1】:

    查看 ctiime 的手册页 - 年份字段是从 1900 年开始的年份。

    http://linux.die.net/man/3/ctime

    tm_year
    The number of years since 1900.
    

    【讨论】:

    • 谢谢,我知道了。我在我的计划中的周一和一年都做错了
    • @vodkhang,很多人都会犯这个错误。这就是为什么第一道防线是阅读手册页。
    猜你喜欢
    • 2020-08-21
    • 2016-04-23
    • 2020-12-31
    • 1970-01-01
    • 2011-10-05
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多