2013-05-02 31 views
3

我有以下測試代碼來查看gmtime和localtime之間的區別。但他們給我相同的結果:UTC:2013-05-02T13:59:58地方:2013-05-02T13:59:58爲什麼gmtime和localtime給我同樣的結果?

time_t now; 
time(&now); 
tm *pTimeStruct = gmtime(&now); 
tm *plocalTimeStruct = localtime(&now); 

string timeStr = ""; 
char timeBuf[64] = {'\0'}; 

sprintf(timeBuf,"UTC:%-4.4d-%-2.2d-%-2.2dT%-2.2d:%-2.2d:%-2.2d " 
    "Local:%-4.4d-%-2.2d-%-2.2dT%-2.2d:%-2.2d:%-2.2d", 
    (pTimeStruct->tm_year + 1900), 
    (pTimeStruct->tm_mon + 1), 
    pTimeStruct->tm_mday, 
    pTimeStruct->tm_hour, 
    pTimeStruct->tm_min, 
    pTimeStruct->tm_sec, 
    (plocalTimeStruct->tm_year + 1900), 
    (plocalTimeStruct->tm_mon + 1), 
    plocalTimeStruct->tm_mday, 
    plocalTimeStruct->tm_hour, 
    plocalTimeStruct->tm_min, 
    plocalTimeStruct->tm_sec); 

timeStr += timeBuf; 
cout << timeStr << endl; 

編輯:

我在東部時間區。

EDIT2:

更新的代碼使用DIFF結構,但得到了同樣的結果:

 time_t now; 
     time(&now); 
     time_t now2; 
     time(&now2); 
     tm *pTimeStruct = gmtime(&now); 
     tm *plocalTimeStruct = localtime(&now2); 
+0

你在什麼系統上? – 2013-05-02 18:06:22

+0

linux機器,fedora – 5YrsLaterDBA 2013-05-02 18:14:49

回答

7

您需要在兩個電話之間的值複製到gmtimelocaltime

的返回值指向一個靜態分配的結構,它可能會被隨後調用的任何日期和時間函數覆蓋。

說我的系統上的手冊頁。這是至少在Linux上的常見行爲。

+0

'tm gmtimestruct; memcpy(&gmtimestruct,gmtime(&now),sizeof gmtimestruct);'會按預期行事。 – wallyk 2013-05-02 18:13:24

+0

請參閱我的更新,使用不同的結構,相同的結果。 – 5YrsLaterDBA 2013-05-02 18:20:32

+2

@ 5YrsLaterDBA您仍然沒有*複製通話的結果*。你只是將相同的指針存儲在兩個不同的地方。例如'tm timeStruct = * gmtime(&now);' – 2013-05-02 18:21:55

0

我也有這個問題,通過使用memcpy的解決了這個問題:

time_t t = time(NULL); 

tm* gmt = (tm*)malloc(sizeof(tm)); 
memcpy(gmt, gmtime(&t), sizeof(tm)); 

tm* loc = localtime(&t); 

cout << asctime(gmt) << endl; 
cout << asctime(loc) << endl; 

free(gmt); 
2

您還可以使用gmtime_r和則localtime_r,這是線程安全的數據存儲在用戶提供的結構。

struct tm *gmtime_r(const time_t *timep, struct tm *result); 
struct tm *localtime_r(const time_t *timep, struct tm *result); 

Windows用戶注意事項:_gmtime_s和_localtime_s是Microsoft版本。

errno_t _gmtime_s(struct tm* _tm, const __time_t* time); 
errno_t _localtime_s(struct tm* _tm, const time_t *time); 
相關問題