繁体   English   中英

如何在C ++中将struct tm转换为time_t

[英]how to convert struct tm to time_t in c++

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

}

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

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

mktime(3)手册页中

time_t ...表示自1970年1月1日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;
}

通常, 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM