C++ mktime 返回随机日期

标签 c++ c datetime time

我正在尝试将日期字符串转换为 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/

相关文章:

c - 指针不能与整数比较?

javascript - 如何在javascript中将字符串解析为特定的日期格式

c++ - 你能在 C++ 的 string::iterator 中使用 advance() 吗?

c++ - 使用私有(private)变量获取正确值时遇到问题

c++ - 内存问题,不知道为什么。什么():std::bad_alloc

c - 写入多个文件会出现段错误,单个文件不会

c - pipe2(...) vs pipe() + fcntl(...),为什么不同?

python - 如何使用python从csv中的同一列拆分日期和时间?

SQL 查找具有下一个最佳时间戳匹配的行对

C++ - 使用 ofstream 在不同的目录中创建文件?