gpt4 book ai didi

C++ mktime 返回随机日期

转载 作者:太空狗 更新时间:2023-10-29 19:52:20 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com