2013-10-22 24 views
3

我有一個在C++中使用strptime()函數的問題。使用strptime將字符串轉換爲時間,但得到垃圾

我在下面的stackoverflow中找到了一段代碼,我想在struct tm上存儲字符串時間信息。儘管我應該獲得關於tm tm_year變量的年度信息,但我總是得到一些垃圾。是否有人可以幫助我?提前致謝。

string s = dtime; 
    struct tm timeDate; 
    memset(&timeDate,0,sizeof(struct tm)); 
    strptime(s.c_str(),"%Y-%m-%d %H:%M", &timeDate); 
    cout<<timeDate.tm_year<<endl; // in the example below it gives me 113 
    cout<<timeDate.tm_min<<endl; // it returns garbage 
**string s will be like "2013-12-04 15:03"** 
+0

@Kunal它始終是YYYY-MM-DD HH-MM喜歡2013年12月4日15:03 – caesar

回答

8
cout<<timeDate.tm_year<<endl; // in the example below it gives me 113 

它應該給你值由1900所以如果它給你113這意味着今年是2013下降。月份也將減少1,即如果它給你1,它實際上是2月份。只需添加這些值:

#include <iostream> 
#include <sstream> 
#include <ctime> 

int main() { 
    struct tm tm; 
    std::string s("2013-12-04 15:03"); 
    if (strptime(s.c_str(), "%Y-%m-%d %H:%M", &tm)) { 
     int d = tm.tm_mday, 
      m = tm.tm_mon + 1, 
      y = tm.tm_year + 1900; 
     std::cout << y << "-" << m << "-" << d << " " 
        << tm.tm_hour << ":" << tm.tm_min; 
    } 
} 

輸出2013-12-4 15:3

+0

有沒有辦法阻止它?我的意思是我想要得到它作爲字符串給出的內容?例如,如果s是「2017-04-15 04:15」我想存儲tm_year 2017 tm_month = 04和tm_min = 15?我怎麼能這樣做? @LihO – caesar

+0

明白了,唯一的辦法就是製作一些這樣的技巧。非常感謝 – caesar

相關問題