2013-10-22 25 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

相关问题