我必须做两个转换函数,从 time_t 到 tm 和从 tm 到 time_t。
这是第一个:
string2time(string str){
time_t rawtime;
time(&rawtime);
tm* timeInfo = localtime(&rawtime);
stringstream ss(str);
string date;
string time;
getline(ss,date,' ');
getline(ss,time,' ');
string word;
//now we work with date..
stringstream sdate(date);
getline(sdate,word,'-');
timeInfo->tm_year = atoi(word.c_str()) -1900;
getline(sdate,word,'-');
timeInfo->tm_mon = atoi(word.c_str())-1;
getline(sdate,word,'-');
timeInfo->tm_mday = atoi(word.c_str());
//and time...
stringstream stime(time);
getline(stime,word,':');
timeInfo->tm_hour = atoi(word.c_str());
getline(stime,word,':');
timeInfo->tm_min = atoi(word.c_str());
getline(stime,word,':');
timeInfo->tm_sec = atoi(word.c_str());
return mktime(timeInfo);
}
这是第二个:
time2str(time_t t){
tm* myT;
myT = localtime(&t);
//here i have to explore myT structure in order to build a proper string
}
无论如何我得到了错误的值..从 tm 结构中的 2013-03-10 00:00:00 开始我得到 2013-04-21 18:16:29 ...为什么?
编辑:取得了一些进展!此代码一直有效,但当小时为 00 时!