time_t to string back and forth in windows

爱⌒轻易说出口 提交于 2020-01-14 04:25:14

问题


I have 2 functions. First one converts time_t to string. Second one string to time_t. I just have the date that needs to be converted and restored back as string.

The functions are

void split(const string &s, char delim, vector<string>& elems) {
    stringstream ss(s); string item; 
    while(getline(ss, item, delim)) { elems.push_back(item);} return;
}

time_t getDateInTimeTfromHyphenSplitString(string s)
{
    struct tm tmvar = {0};
    vector<string> tim;
    split(s.c_str(),'-',tim);
    tmvar.tm_year = atoi(tim[2].c_str()) - 1900;
    tmvar.tm_mon = atoi(tim[1].c_str());
    tmvar.tm_mday = atoi(tim[0].c_str());
    tmvar.tm_isdst = 0;
    time_t ttm = mktime(&tmvar);
    return ttm;
}

string getDateInHyphenSplitStringfromTimeT(time_t t)
{
    struct tm *timeinfo = (tm*)malloc(sizeof(tm));
    gmtime_s(timeinfo, &t);
    char *buffer = NULL;
    buffer = (char*)malloc((size_t)20);
    strftime(buffer, 20, "%d-%m-%Y", timeinfo);
    string s = buffer ;
    return s;
}

Now when I test this code with following lines the out put seems strange.

string sk = "31-12-2010";
cout << sk << endl;
time_t ttk = getDateInTimeTfromHyphenSplitString(sk);
sk = getDateInHyphenSplitStringfromTimeT(ttk );

cout << sk << endl;

Input :- 31-12-2010 Output:- 30-01-2011

Strangely I am getting 1 month difference for any date that I supply as input.

Please let me know, if how to get the correct time back.

PS: I choose this technique because I need to format date with '-'s.


回答1:


tm_mon counts the "months since January", thus ranging in value from 0 to 11.

You need to subtract 1 from the input month.


Apart from that, your code leaks memory: You never free your malloced memory. Since you are programming in C++, I'd recommend not using malloc/free altogether, but new, new[], delete and delete[] instead, as malloc has no notion of objects and doesn't call constructors.

In the special case of your function, you wouldn't even need dynamic memory allocation at all:

    struct tm timeinfo;
    gmtime_s(&timeinfo, &t);
    char buffer[20];
    strftime(buffer, sizeof(buffer), "%d-%m-%Y", &timeinfo);


来源:https://stackoverflow.com/questions/13842369/time-t-to-string-back-and-forth-in-windows

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