给定的函数是用于处理日期和时间的类的一部分。我解析的文件需要将给定的字符串数据转换为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;
}
最佳答案
从mktime(3) man page:
然后,您拥有struct tm
的字段,尤其是这一字段:
因此,基本上,如果将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;
}