【问题标题】:Conversion from SYSTEMTIME to time_t gives out Time in UTC/GMT从 SYSTEMTIME 到 time_t 的转换给出了 UTC/GMT 时间
【发布时间】:2015-04-26 02:24:44
【问题描述】:

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

【问题讨论】:

  • 是的,手册说 mktime() 从本地时间转换为 UTC。根据 time_t 的要求,它存储自 1970 年 1 月 1 日凌晨 12 点 UTC 以来的秒数。功能,而不是错误。
  • 使用 _mkgmtime() 它只是在两者之间进行转换而不考虑时区。
  • 您的解释有些混乱:SYSTEMTIME 包含什么?当地时间还是 UTC 时间?
  • SYSTEMTIME 始终是本地时间。
  • 然后mktime 做你想做的事,有两个注意事项:C 库的时区概念必须与系统的概念同步,tm 结构中的 tm_isdst 标志必须正确设置。检查SYSTEMTIME 结构中的类似字段。

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


【解决方案1】:

我终于通过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;
}

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

【讨论】:

    猜你喜欢
    • 2011-07-31
    • 2018-01-08
    • 2010-09-15
    • 2014-11-05
    • 1970-01-01
    • 2014-11-29
    • 2015-11-09
    相关资源
    最近更新 更多