从SYSTEMTIME到time_t的转换以UTC/GMT表示时间

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

本文关键字:UTC GMT 时间 表示 转换 SYSTEMTIME time      更新时间:2023-10-16

我正在尝试通过在各种论坛中找到的实现将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);
}

但令我惊讶的是,tm携带的数据对应于当地时间,但mktime()返回的time_t对应于UTC时间。

是这样工作的,还是我遗漏了什么?

感谢您的提前帮助!!

编辑1:我想将携带我的本地时间的SYSTEMTIME准确地转换为time_t

我在基于VC6的MFC应用程序中使用这个。

第2版:修改后的代码。

我终于从Windows SDK中找到了解决方案,通过TIME_ZONE_INFORMATION和_timezone

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

编辑1:请添加您的评论,如果您看到任何错误,请随时评论或编辑。谢谢