2016-07-27 122 views
1

我試圖將格式爲HHMMSS.SS,DD,MM,YYYY的時間轉換爲unix時間。問題是,然後調用mktime,返回相同的time_t。mktime每次返回相同的值

ConvertTime(std::string input) 
{ 
    std::vector<std::string> tokens; 

    //splits input into tokens 
    Tokenize(input, tokens); 

    int hrs = atoi(tokens.at(0).substr(0,2).c_str()); 
    int mins = atoi(tokens.at(0).substr(2,2).c_str()); 
    int secs = atoi(tokens.at(0).substr(4,2).c_str()); 
    int day = atoi(tokens.at(1).c_str()); 
    int month = atoi(tokens.at(2).c_str()); 
    int year = atoi(tokens.at(3).c_str()); 

    struct tm tm = {0}; 
    time_t msgTime = 0; 

    tm.tm_sec = secs; 
    tm.tm_min = mins; 
    tm.tm_hour = hrs; 
    tm.tm_mday = day; 
    tm.tm_mon = month-1; 
    tm.tm_year = year-1900; 
    tm.tm_isdst = -1; 
    msgTime = mktime(&tm); 
    printf("time: %f\n",msgTime); 

} 

Input ex: 
154831.90,22,07,2016 
154832.10,22,07,2016 
154832.30,22,07,2016 
154832.50,22,07,2016 
154832.70,22,07,2016 
154832.90,22,07,2016 
154833.10,22,07,2016 

Output ex: 
1469202560.00 
1469202560.00 
1469202560.00 
1469202560.00 
1469202560.00 
1469202560.00 
1469202560.00 

我覺得我沒有初始化的東西,或者值不被改變,但ConvertTime的調用之間的tm結構不應該被結轉,所以我不知道是什麼問題是。

+0

'msgTime'是'time_t',但'printf()的'是試圖打印一個'雙'...先施放。 – Dmitri

+0

time_t通常是一個整數值。您應該首先將您的C代碼轉換爲C++:使用std :: cout來避免任何轉換 – wasthishelpful

+0

在指責'mktime'之前查看'Tokenize'的結果 –

回答

1

這裏的問題是嘗試使用time_t(msgTime)值作爲double,而不進行轉換。

的解決方案是簡單地投MSGTIME到雙像這樣:

printf("time %f\n",(double)msgTime); 

這使得功能:

ConvertTime(std::string input) 
{ 
    std::vector<std::string> tokens; 

    //splits input into tokens 
    Tokenize(input, tokens); 

    int hrs = atoi(tokens.at(0).substr(0,2).c_str()); 
    int mins = atoi(tokens.at(0).substr(2,2).c_str()); 
    int secs = atoi(tokens.at(0).substr(4,2).c_str()); 
    int day = atoi(tokens.at(1).c_str()); 
    int month = atoi(tokens.at(2).c_str()); 
    int year = atoi(tokens.at(3).c_str()); 

    struct tm tm = {0}; 
    time_t msgTime = 0; 

    tm.tm_sec = secs; 
    tm.tm_min = mins; 
    tm.tm_hour = hrs; 
    tm.tm_mday = day; 
    tm.tm_mon = month-1; 
    tm.tm_year = year-1900; 
    tm.tm_isdst = -1; 
    msgTime = mktime(&tm); 
    printf("time: %f\n",(double)msgTime); 

} 

Input ex: 
154831.90,22,07,2016 
154832.10,22,07,2016 
154832.30,22,07,2016 
154832.50,22,07,2016 
154832.70,22,07,2016 
154832.90,22,07,2016 
154833.10,22,07,2016 

Output ex: 
1469202511.00 
1469202512.00 
1469202512.00 
1469202512.00 
1469202512.00 
1469202512.00 
1469202513.00 
+0

好的答案。 'time_t'是一些標量類型('int','long long','long double'等)。如果代碼需要'printf()'作爲'double '。我們可能使用'cout <<'作爲OP的代碼可能是C++。 – chux

相關問題