给定的函数是用于处理日期和时间的类的一部分。我解析的文件需要将给定的字符串数据转换为time_t但mktime不起作用。为什么呢?
struct tm DateTimeUtils::makeTime(string arrTime)//accepts in format"2315"means 11.15 pm
{
struct tm neww;
string hour = arrTime.substr(0,2);
int hour_int = stoi(hour);
neww.tm_hour=hour_int;//when this is directly printed generates correct value
string minute = arrTime.substr(2,2);
int minute_int = stoi(minute);
neww.tm_min=(minute_int);//when this is directly printed generates correct value
time_t t1 = mktime(&neww);//only returns -1
cout<<t1;
return neww;
}
答案 0 :(得分:0)
在使用之前清除结构通常有助于这种情况:
struct tm neww;
memset((void *)&neww, 0, sizeof(tm));
答案 1 :(得分:0)
time_t
...表示自纪元,1970-01-01 00:00:00 +0000(UTC)以来经过的秒数。
然后你有struct tm
的字段,尤其是这个字段:
tm_year
自1900年以来的年数。
如果将tm_year
设置为0
并且我们正确地进行数学计算,那么我们会得到一个70
年的差异需要以秒为单位表示,并且这可能太大了
您可以通过将struct tm
值初始化为Epoch并将其用作基准参考来解决此问题:
struct tm DateTimeUtils::makeTime(string arrTime)//accepts in format"2315"means 11.15 pm
{
time_t tmp = { 0 };
struct tm neww = *localtime(&tmp);
string hour = arrTime.substr(0,2);
int hour_int = stoi(hour);
neww.tm_hour=hour_int;//when this is directly printed generates correct value
string minute = arrTime.substr(2,2);
int minute_int = stoi(minute);
neww.tm_min=(minute_int);//when this is directly printed generates correct value
time_t t1 = mktime(&neww);//only returns -1
cout<<t1;
return neww;
}
答案 2 :(得分:0)
通常time_t
被定义为64位整数,其解析范围为
-2 ^ 63至+ 2 ^ 63-1(-9223372036854775808至+9223372036854775807)
大约从-292个bilion年到+292年。
然而。如果,出于某种原因,在您的系统上time_t
被定义为32位整数(16位嵌入式系统或奇怪的架构或头文件),我们从
2 ^ 31至2 ^ 31-1(-2147483648至+2147483647)
大致从-68岁到+68岁。您可以在致电mktime()
之前重新定义time_t来解决此问题。
#define time_t long int
或者是否真的使用16位系统
#define time_t long long int