using strptime converting string to time but getting garbage

亡梦爱人 提交于 2019-12-07 03:58:19

问题


I have a problem with using strptime() function in c++.

I found a piece of code in stackoverflow like below and I want to store string time information on struct tm. Although I should get year information on my tm tm_year variable, I always get a garbage.Is there anyone to help me ? Thanks in advance.

    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"**

回答1:


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

it is supposed to give you value decreased by 1900 so if it gives you 113 it means the year is 2013. Month will also be decreased by 1, i.e. if it gives you 1, it is actually February. Just add these values:

#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;
    }
}

outputs 2013-12-4 15:3



来源:https://stackoverflow.com/questions/19524720/using-strptime-converting-string-to-time-but-getting-garbage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!