如何在 C++ 中将结构 TM 转换为time_t



给定函数是用于处理日期和时间的类的一部分。我解析的文件需要将给定的字符串数据转换为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) 手册页:

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

在这种情况下,在使用前清除结构通常会有所帮助:

struct tm neww;
memset((void *)&neww, 0, sizeof(tm));

通常time_t被定义为64位整数,其解析范围为

-2^63 至 +2^63-1 (-9223372036854775808 至 +9223372036854775807)

这大约是从纪元的-292年到+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

最新更新