我正在尝试将日期字符串转换为 time_t
,但 mktime() 返回看似随机的日期:
string datetime = "2014-12-10 10:30";
struct tm tmInfo;
strptime(datetime.c_str(), "%Y-%m-%d %H:%M", &tmInfo);
tmInfo.tm_isdst = 0;
time_t eventTime = mktime(&tmInfo);
eventTime 从 1970 年代到 2030 年代变化很大。 tmInfo 结构保存了正确的日期,所以错误一定发生在 mktime() 中。有什么问题吗?
最佳答案
在调用 strptime()
之前,您需要正确地对 struct tm
实例的所有其他字段进行零初始化,因为它不一定会初始化每个字段。来自strptime()
POSIX specification :
It is unspecified whether multiple calls to strptime() using the same tm structure will update the current contents of the structure or overwrite all contents of the structure. Conforming applications should make a single call to strptime() with a format and all data needed to completely specify the date and time being converted.
例如,这就足够了:
struct tm tmInfo = {0};
关于C++ mktime 返回随机日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27351239/