2016-07-27 11 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 

私は何かを初期化していないよような気がします、または値が変更されていないが、TMの構造体は、ConvertTimeの呼び出しの間繰り越すべきではありませんので、私は何の問題がわからないんだけどです。

+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'など)です。 'double(double)'として出力するには 'printf()'が必要です。 '。私たちの多分OPのコードとして 'cout <<'を使うのはおそらくC++でしょう。 – chux

関連する問題