2011-02-06 312 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; 
}