2011-02-06 29 views
0

< time.h>を使用して、文字列と日付をC++で変換しています。日付を文字列に変換するC++

int main() { 
    string dateFormat = "%m-%d-%Y %H:%M:%S"; 
    tm startDate, endDate; 
    if (strptime("1-1-2004 01:01:01", &dateFormat[0], &startDate) == NULL) { exit(1); } 
    if (strptime("1-1-2010 00:00:00", &dateFormat[0], &endDate) == NULL) { exit(1); } 
    cout << "startDate: " << asctime(&startDate) 
     << " endDate: " << asctime(&endDate) << endl; 

    time_t startDate2 = mktime(&startDate); 
    time_t endDate2 = mktime(&endDate); 

    cout << "startDate: " << asctime(localtime(&startDate2)) 
     << " endDate: " << asctime(localtime(&endDate2)) << endl; 
    return 0; 
} 

私は出力としてこれを取得:

startDate: Thu Jan 1 01:01:01 2004 
endDate: Thu Jan 1 01:01:01 2004 

startDate: Thu Jan 1 01:01:01 2004 
endDate: Thu Jan 1 01:01:01 2004 

なぜ開始日が終了日と同じですか?また、誰かがこれを行うより良い方法を持っている場合は、話してください。

答えて

0

私はそれを理解しました。 asctimeは文字列を書き込むために共有メモリを使います。私は上書きされないように別の文字列にコピーする必要があります。

int main() { 
    string dateFormat = "%m-%d-%Y %H:%M:%S"; 
    tm startDate, endDate; 
    if (strptime("1-1-2004 01:01:01", &dateFormat[0], &startDate) == NULL) { exit(1); } 
    if (strptime("1-1-2010 00:00:00", &dateFormat[0], &endDate) == NULL) { exit(1); } 

    string sd1(asctime(&startDate)); 
    string ed1(asctime(&endDate)); 

    cout << "startDate: " << sd1 
     << " endDate: " << ed1 << endl; 

    time_t startDate2 = mktime(&startDate); 
    time_t endDate2 = mktime(&endDate); 

    string sd2(asctime(localtime(&startDate2))); 
    string ed2(asctime(localtime(&endDate2))); 

    cout << "startDate: " << sd2 
     << " endDate: " << ed2 << endl; 
    return 0; 
} 
関連する問題