【发布时间】:2013-04-21 16:00:52
【问题描述】:
我要做两个转换函数,从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
}
无论如何我得到了错误的值..从 2013-03-10 00:00:00 开始 在 tm 结构中我得到 2013-04-21 18:16:29 ... 为什么?
编辑: 取得了一些进展!此代码一直有效,但小时为 00 时!
【问题讨论】:
-
这里有一个提示:110 似乎是 年 中的某天,而不是该月中的某天(当天)
-
是的,我打错了字段,反正还是不行……
-
你是怎么调用这些函数的?
-
?你能解释一下你的意思吗?
-
那么 time() 函数获取当前时间。因此它将覆盖该函数的任何输入。所以我很好奇您希望如何使用这些功能?
标签: c++ c visual-c++