2

我正在尝试使用strptime()将日期/时间字符串解析为其组件值。作为测试,我尝试使用以下代码解析固定的日期时间字符串并打印结果值:

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

int main(void)
{
        struct tm tm;
        memset(&tm, 0, sizeof(struct tm));
        strptime("2001/11/12 18:31:01", "%Y/%m/%d %H:%M:%S", &tm);
        printf("year: %d; month: %d; day: %d;\n",
                        tm.tm_year, tm.tm_mon, tm.tm_mday);
        printf("hour: %d; minute: %d; second: %d\n",
                        tm.tm_hour, tm.tm_min, tm.tm_sec);
        exit(EXIT_SUCCESS);
}

我得到的输出是:

year: 101; month: 10; day: 12;
hour: 18; minute: 31; second: 1

其他值看起来不错,但年份和月份与输入 ( ) 不匹配2001/11/12 18:31:01。这是为什么?

4

1 回答 1

5

在 C 中的 astruct tm中,年份是自 1900 年以来的年数,月份是从零开始的(0 = 一月)。

因此,您的日期输出语句应为:

printf("year: %d; month: %d; day: %d;\n",
    tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);

ISO C117.25.1 Components of time如此声明(尽管这种行为可以追溯到很久以前):

tm结构应至少包含以下成员,以任意顺序排列。成员的语义及其正常范围在注释中表达。

int tm_sec;     // seconds after the minute — [0, 60]
int tm_min;     // minutes after the hour — [0, 59]
int tm_hour;    // hours since midnight — [0, 23]
int tm_mday;    // day of the month — [1, 31]
int tm_mon;     // months since January — [0, 11]
int tm_year;    // years since 1900
int tm_wday;    // days since Sunday — [0, 6]
int tm_yday;    // days since January 1 — [0, 365]
int tm_isdst;   // Daylight Saving Time flag
于 2013-11-11T13:03:18.270 回答