Frage

I'm trying to use strptime() to parse a date / time string into its component values. As a test, I tried to parse a fixed datetime string and print the resulting values, using the following code:

#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);
}

The output I get is:

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

The other values look good, but the year and month don't match the input (2001/11/12 18:31:01). Why is that?

War es hilfreich?

Lösung

In a struct tm in C, the year is the number of years since 1900, and the month is zero-based (0 = January).

Hence your output statement for the date should be:

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

ISO C11 7.25.1 Components of time states it thus (though this behaviour goes way back):

The tm structure shall contain at least the following members, in any order. The semantics of the members and their normal ranges are expressed in the comments.

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top