我正在尝试将接收到的日期时间转换为特定格式以插入到 MySQL 数据库中。该程序是用 C++ 编写的,以下解决方案有效,但我觉得它效率低得可怕。
输入是:Mon Nov 08 17:41:23 +0000 2010
所需的输出格式为:YYYY-MM-DD HH:MM:SS
所以对于这个例子,输出将是:2010-11-08 17:41:23
我已经包含了代码的相关部分。
//class variable
std::map<std::string, std::string> monthMap;
void processor::initializeMonthMap(){
monthMap["Jan"] = "01";
monthMap["Feb"] = "02";
monthMap["Mar"] = "03";
monthMap["Apr"] = "04";
monthMap["May"] = "05";
monthMap["Jun"] = "06";
monthMap["June"] = "06";
monthMap["Jul"] = "07";
monthMap["July"] = "07";
monthMap["Aug"] = "08";
monthMap["Sept"] = "09";
monthMap["Sep"] = "09";
monthMap["Oct"] = "10";
monthMap["Nov"] = "11";
monthMap["Dec"] = "12";
}
inline std::string processor::convertDate(std::string input) {
//Format: Mon Nov 08 17:41:23 +0000 2010
//To get to YYYY-MM-DD HH:MM:SS
std::stringstream newString(input);
std::string temp1;
std::string temp2;
// Read Day in txt, discard
newString >> temp1;
//Read month, convert to number
newString >> temp1;
temp2 = "-" + monthMap[temp1] + "-";
//Read Day in number
newString >> temp1;
temp2.append(temp1 + " ");
//Read TimeStamp
newString >> temp1;
temp2.append(temp1);
//Discard UTM adjustment
newString >> temp1;
//Read year
newString >> temp1;
//Add year to beginning of input
temp1.append(temp2);
return temp1;
}
最佳答案
您正在解析字符串,幸运的是您可以通过简单的追加来构建输出。我认为这并没有变得更有效率。
但是,您似乎可以使用 seekg 将光标定位到星期几和 UTM 调整之后。
关于c++ - 从字符串中标记/提取信息的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4752605/