2015-02-24 66 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: 請不要發表您的評論,也如果你看到任何錯誤,隨意評論或編輯。謝謝。