简体   繁体   English

从SYSTEMTIME转换为time_t会给出UTC / GMT中的时间

[英]Conversion from SYSTEMTIME to time_t gives out Time in UTC/GMT

I am trying to convert SYSTEMTIME to time_t through the implementation I found in various forums. 我正在尝试通过各种论坛中的实现将SYSTEMTIME转换为time_t

time_t TimeFromSystemTime(const SYSTEMTIME * pTime)
{
    struct tm tm;
    memset(&tm, 0, sizeof(tm));

    tm.tm_year = pTime->wYear - 1900; // EDIT 2 : 1900's Offset as per comment
    tm.tm_mon = pTime->wMonth - 1;
    tm.tm_mday = pTime->wDay;

    tm.tm_hour = pTime->wHour;
    tm.tm_min = pTime->wMinute;
    tm.tm_sec = pTime->wSecond;
    tm.tm_isdst = -1; // Edit 2: Added as per comment

    return mktime(&tm);
}

But to my surprise, the tm is carrying the data corresponds to the local time but the mktime() returns the time_t corresponds to the time in UTC. 但是令我惊讶的是, tm承载的数据对应于本地时间,但是mktime()返回的time_t对应于UTC时间。

Is this the way it works or am I missing anything here? 这是它的工作方式还是我在这里错过了任何东西吗?

Thanks for the help in advance !! 我在这里先向您的帮助表示感谢 !!

EDIT 1: I want to convert the SYSTEMTIME which carries my Local time as the time_t exactly. 编辑1:我想转换SYSTEMTIME准确地将我的本地时间作为time_t

I am using this in the VC6 based MFC application. 我在基于VC6的MFC应用程序中使用它。

EDIT 2: Modified Code. 编辑2:修改的代码。

I finally found the Solution from the Windows SDK, through TIME_ZONE_INFORMATION and _timezone 我终于通过TIME_ZONE_INFORMATION_timezone从Windows SDK找到了解决方案

time_t GetLocaleDateTime( time_t ttdateTime) // The time_t from the mktime() is fed here as the Parameter
{
    if(ttdateTime <= 0)
        return 0;

    TIME_ZONE_INFORMATION tzi;

    GetTimeZoneInformation(&tzi); // We can also use the StandardBias of the TIME_ZONE_INFORMATION

    int iTz = -_timezone; // Current Timezone Offset from UTC in Seconds

    iTz = (iTz >  12*3600) ? (iTz - 24*3600) : iTz; // 14  ==> -10
    iTz = (iTz < -11*3600) ? (iTz + 24*3600) : iTz; // -14 ==> 10

    ttdateTime += iTz;

    return ttdateTime;
}

EDIT 1 : Please do add your comments, and also if you see any bugs feel free to comment or edit. 编辑1 :请添加您的评论,如果您发现任何错误,请随时评论或编辑。 Thanks. 谢谢。

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

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