c++ - 从 SYSTEMTIME 到 time_t 的转换给出 UTC/GMT 时间

标签 c++ c visual-c++ time mfc

我正在尝试通过在各种论坛中找到的实现将 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:修改代码。

最佳答案

我终于通过 TIME_ZONE_INFORMATION 从 Windows SDK 找到了解决方案和 _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: 请添加您的评论,如果您发现任何错误,请随时评论或编辑。谢谢。

关于c++ - 从 SYSTEMTIME 到 time_t 的转换给出 UTC/GMT 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28696211/

相关文章:

c# - 使用 ISDN 调制解调器 (C#) 在第一次 bip 后调用电话号码时挂断

c++ - 将 32 位 directx9 应用程序转换为大地址感知

c - 如何在不区分大小写的字符串中查找单词?

c# - 加载/卸载 C dll 时出现 C# 问题

c - 我应该如何打印像 off_t 和 size_t 这样的类型?

c - _aenvptr 和 _wenvptr 的重复定义

c++ - 如何编写支持 LTO 的代码?

c++ - "Blocking"下一个 cout

c++ - 如何将图像传递到C++可执行文件并将输出图像存储在新目录中?

c++ - 文件中存储的对象的字符串成员