Johannes
Johannes

Reputation: 6707

mktime does not update the struct tm

I am using VS2010 This code is compiled as an ANSI C Project

int C90Clockadapter_GetCW_ISO8601(const C90Clockadapter * clockadapter, int * calendarweek)
{
    int e = 0;
    struct tm tm;
    char timebuf[64];

    memset( &tm, 0, sizeof( tm ) );
    tm.tm_mday = clockadapter->mDay;
    tm.tm_mon = clockadapter->mMonth;
    tm.tm_year = clockadapter->mYear;

    mktime(&tm);  

    if (0 != strftime(timebuf,sizeof(timebuf),"%W", &tm) ) //i know %W is not ISO8601
    {
        *calendarweek = atoi(timebuf);
    }
    else
    {
        e |= 1;
    }

    return e;
}

somehow mktime(&tm) does not change the state of tm. This behaviour completely does not fit my expectation.

I wrote some unittests that have a self explaining output:

4.1.1971 - expected CW 1 but was CW 0
31.12.1992 - expected CW 53 but was CW 0

What is wrong with my code - or is there some speciality in windows or with vs2010 and ansi-c that i am missing?

Upvotes: 1

Views: 511

Answers (2)

Johannes
Johannes

Reputation: 6707

The timeformat was invalid. mktime returned -1 and that was unhandled.

This snippet shows how to correctly fill the struct tm.

tm.tm_mday = clockadapter->mDay;
tm.tm_mon = clockadapter->mMonth - 1;
tm.tm_year = clockadapter->mYear - 1900;

Upvotes: 0

m24p
m24p

Reputation: 674

The references says it won't necessarily modify the timeptr parameter. You should use the return value. See http://www.cplusplus.com/reference/ctime/mktime/

time_t mktime (struct tm * timeptr);

Upvotes: 1

Related Questions