mktime不会更新struct tm

时间:2014-02-05 20:34:13

标签: c visual-studio-2010

我正在使用VS2010 此代码编译为ANSI C项目

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

某种程度上mktime(&tm)不会改变tm的状态。这种行为完全不符合我的期望。

我写了一些具有自我解释输出的单元测试:

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

我的代码有什么问题 - 或者在Windows中是否有某些专业或者我缺少vs2010和ansi-c?

2 个答案:

答案 0 :(得分:1)

参考文献说它不一定会修改timeptr参数。您应该使用返回值。见http://www.cplusplus.com/reference/ctime/mktime/

time_t mktime (struct tm * timeptr);

答案 1 :(得分:0)

时间格式无效。 mktime返回-1,那是未处理的。

此代码段显示了如何正确填写struct tm

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