tm中使用c++结构时,我得到的tm_wday值是大整数(例如4199040,远大于预期的0-6范围:)。为什么会这样?所有其他值(例如年,月等)都是正确的。

我已经看过以前的问题,其中似乎似乎错误地计算了工作日,即是0-6范围内的不同值,这是由于时区差异等导致的。但是我困惑为什么我会得到这么大的数字呢?它似乎也不是内存位置(不是十六进制格式的数字)。

#include <stdio.h>
#include <iostream>
#include <time.h>


struct tm get_time(std::string timestamp_string = "2019.08.16D11:00:00"){

    struct tm tm;
    int hh, mm;
    int MM, DD, YY;
    float ss;
    const char * timestamp = timestamp_string.c_str();
    if (sscanf(timestamp,"%d.%d.%dD%d:%d:%f", &YY,&MM, &DD,&hh, &mm,&ss) != 6) std::cout<<"oops";

    tm.tm_year = YY - 1900;  // Years from 1900
    tm.tm_mon = MM - 1; // Months form January
    tm.tm_mday = DD;
    tm.tm_hour = hh;
    tm.tm_min = mm;
    tm.tm_sec = ss;
    tm.tm_isdst = 0;
    return tm;

}

int main(){
    struct tm tm = get_time("2019.08.16D11:00:00");
    std::cout<<"Year is: "<<tm.tm_year<<std::endl; //119 - is correct
    std::cout<<"Month since Jan is: "<<tm.tm_mon<<std::endl; //7 - is correct
    std::cout<<"Weekday is: "<<tm.tm_wday<<std::endl;//4199040- why is this so large?

    return 0;
}

最佳答案

环顾四周,可以期望在定义tm结构之后,使用对实例的引用来运行函数mktime(),以便更新派生的值(例如tm_wday)。因此,固定的main()函数应为:

int main(){
    struct tm tm = get_time("2019.08.16D11:00:00");
    mktime(&tm); //needs to be called to update derived values such as tm_wday
    std::cout<<"Year is: "<<tm.tm_year<<std::endl; //119 - is correct
    std::cout<<"Month since Jan is: "<<tm.tm_mon<<std::endl; //7 - is correct
    std::cout<<"Weekday is: "<<tm.tm_wday<<std::endl;//shows 5 now - is correct
    return 0;
}

10-08 04:07