2

我不知道我在下面的代码中犯了什么错误,但是使用 Visual c++ 2010 sp1,我粘贴在下面的代码结果显示了一个月的错误。

struct tm timeStamp;
timeStamp.tm_year = 2012 - 1900;
timeStamp.tm_mon = 7;
timeStamp.tm_mday = 19;
timeStamp.tm_hour = 20;
timeStamp.tm_min = 55;
timeStamp.tm_sec = 22;
timeStamp.tm_isdst = -1;


time_t time_val = mktime(&timeStamp);

const int buff_size = 20;
char buff[buff_size] = {0};
strftime(buff, buff_size, "%Y-%m-%d %H:%M:%S", localtime( &time_val ));


cout << "Original time:\t"
    << timeStamp.tm_year + 1900 << "-" << timeStamp.tm_mon << "-" << timeStamp.tm_mday << " "
    << timeStamp.tm_hour << ":" << timeStamp.tm_min << ":" << timeStamp.tm_sec << endl;
cout << "Converted time:\t" << buff << endl;

我编译时此代码的输出结果是:

Original time:  2012-7-19 20:55:22
Converted time: 2012-08-19 20:55:22
4

1 回答 1

2

tm_mon字段struct tm来自0-11,其中 0 == 一月和 11 == 十二月。strftime知道这一点并在内部进行补偿。你cout不能弥补这一点。

C++ 参考页面包含所有值范围的struct tm定义。

于 2012-07-19T16:51:30.140 回答