2015-02-24 46 views
1

我试图通过在各种论坛中找到的实现将SYSTEMTIME转换为time_t从SYSTEMTIME到time_t的转换以UTC/GMT格式提供时间

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:修改后的代码。

+1

是的,手册说mktime()从本地时间转换为UTC。按照time_t的要求,它存储自1970年1月1日上午12点以来的秒数。功能,而不是一个错误。 – 2015-02-24 13:54:26

+0

使用_mkgmtime(),它只是在两者之间进行转换,而不会将时区变为acount。 – 2015-02-24 14:00:59

+0

您的解释有些令人困惑:SYSTEMTIME包含什么?当地时间或UTC时间? – chqrlie 2015-02-24 14:04:10

回答

1

我终于找到了从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: 请不要发表您的评论,也如果你看到任何错误,随意评论或编辑。谢谢。