Pergunta

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"**
Foi útil?

Solução

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top