2016-05-05 74 views
2

我寫了下面的簡單代碼:C++時間()給我幾乎是隨機結果

time_t makeUnixTimeStamp(int year, int month, int day, int hour, int min, int sec) { 
    tm uts_time; 
    uts_time.tm_year = year - 1900; 
    uts_time.tm_mon = month - 1; 
    uts_time.tm_mday = day; 
    uts_time.tm_sec = sec; 
    uts_time.tm_min = min; 
    uts_time.tm_hour = hour; 
    return mktime(&uts_time); 
} 

std::string getReadableDateTime(unsigned int unixTimeStamp) { 
    char dateTime[ 40 ]; 
    time_t someTime = unixTimeStamp; 
    struct tm *mTime; 
    mTime = localtime(&someTime); 
    strftime(dateTime, sizeof(dateTime), "%Y-%m-%d %H:%M:%S", mTime); 
    return std::string(dateTime); 
} 


unsigned int startLogTime = makeUnixTimeStamp(2016, 05, 04, 00, 00, 00); 
time_t nowTime; 
time(&nowTime); 
std::cout << "readable Time = " << getReadableDateTime(startLogTime) << '\n'; 

我得到一些運行後怪輸出。當前顯示時間爲php -r 'echo time();'。 如果我不改變我的代碼中的任何東西,爲什麼我有不同的「可讀時間」?

輸出:

15:20:58 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-04 00:00:00 
1462450865 

15:21:05 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-04 00:00:00 
1462450866 

15:21:06 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-04 00:00:00 
1462450867 

15:21:07 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-03 23:00:00 
1462450868 

15:21:08 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-03 23:00:00 
1462450869 

15:21:09 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-04 00:00:00 
1462450871 

15:21:11 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-03 23:00:00 
1462450872 

15:21:12 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-04 00:00:00 
1462450877 

15:21:17 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-04 00:00:00 
1462450882 

15:21:22 ~ $ rm a.out && g++ analyze.cpp && ./a.out && php -r 'echo time();' 
readable Time = 2016-05-03 23:00:00 
1462450883 

看來,如果我刪除時間()函數 - 它的作品更好,但我最需要它的代碼之後。

回答

1

您應該設置DST標誌。它可能正在隨機初始化

如果夏令時有效,夏令時標誌(tm_isdst)大於零,如果夏令時無效,則爲零;如果信息不可用,則小於零。

http://www.cplusplus.com/reference/ctime/tm/

一個有用的配方以拳頭與當前本地時間初始化tm結構,使這一被設置方式與你的機器上一切一樣。

time_t now = time(0); 
uts_time = * localtime(&now); 
// initialise with the time you really want 
+0

如何正確使用? :) – JavaRunner

+0

你能展示它在我的代碼中的樣子嗎?因爲我得到:候選函數(隱式複製賦值運算符)不可行:對於第一個 參數,沒有從「struct tm *」到「const tm」的已知轉換;用* – JavaRunner

+0

取消引用參數對不起,忘了從本地時間取消引用返回。回答編輯 – ravenspoint

1

你有你的tm結構的某些未初始化的部分:上回讀任何未初始化的部分行爲是不確定

改爲使用類似tm foo{};的代碼,這會導致所有結構元素初始化爲零值(以及指向空指針值的指針)。

+0

'tm uts_time {}'給我:*錯誤:預期';'在宣言結束時* – JavaRunner

+0

你忘了';'? – Bathsheba

+1

這會造成混亂,如果他目前在DST – ravenspoint