使用strtime将字符串转换为时间,但获取垃圾 我在C++中使用了StrutTime-()函数有问题。p>
我在stackoverflow中找到了一段代码,如下所示,我想在struct tm上存储字符串时间信息。虽然我应该在我的tm_year变量上获取年份信息,但我总是得到一个垃圾。有人帮我吗?提前谢谢使用strtime将字符串转换为时间,但获取垃圾 我在C++中使用了StrutTime-()函数有问题。p>,c++,strptime,C++,Strptime,我在stackoverflow中找到了一段代码,如下所示,我想在struct tm上存储字符串时间信息。虽然我应该在我的tm_year变量上获取年份信息,但我总是得到一个垃圾。有人帮我吗?提前谢谢 string s = dtime; struct tm timeDate; memset(&timeDate,0,sizeof(struct tm)); strptime(s.c_str(),"%Y-%m-%d %H:%M", &timeDate);
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"**
string s=dtime;
struct-tm-timeDate;
memset(&timeDate,0,sizeof(struct tm));
strtime(s.c_str(),%Y-%m-%d%H:%m,&timeDate);
库特
输出2013-12-4 15:3
@Kunal它总是YYYY-MM-DD HH-MM像2013-12-04 15:03有什么办法阻止它吗?我的意思是我想得到作为字符串给出的东西?例如,如果s是“2017-04-15 04:15”,我想存储2017年tm月=04和tm分钟=15?我怎么能这么做@LihOgot,唯一的办法就是做一些这样的把戏。非常感谢,您需要调零struct tm
,否则结果未定义。:)应该是struct tm{}代码>?
cout<<timeDate.tm_year<<endl; // in the example below it gives me 113
#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;
}
}