C ++ mktime返回随机日期 [英] C++ mktime returning random dates

查看:115
本文介绍了C ++ mktime返回随机日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期字符串转换为 time_t ,但是mktime()返回看似随机的日期:

I'm trying to convert a date string to a time_t, but mktime() is returning seemingly random dates:

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);

tmInfo struct保存正确的日期,因此错误必须在mktime()中发生。任何有什么问题的想法?

eventTime ranges wildly from the 1970s to the 2030s. The tmInfo struct holds the correct date, so the error must be happening in mktime(). Any ideas of what's going wrong?

推荐答案

您需要对<$ c $的所有其他字段进行适当的零初始化调用 strptime()之前的c> struct tm 实例,因为它不一定要初始化每个字段。从 strptime() POSIX规范

You need to properly zero-initialize all of the other fields of the struct tm instance before calling strptime(), since it doesn't necessarily initialize every field. From the strptime() POSIX specification:


未指定是否使用相同的 strptime() > tm 结构将更新结构的当前内容或覆盖结构的所有内容。符合应用程序应该使用格式和所有数据完整指定要转换的日期和时间的单一调用strptime()。

例如,这应该足够了:

struct tm tmInfo = {0};

这篇关于C ++ mktime返回随机日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆